WPF customcontroltemplate在运行时更新TemplateBinding

本文关键字:更新 TemplateBinding 运行时 customcontroltemplate WPF | 更新日期: 2023-09-27 18:05:14

我一直在尝试使用WPF并使用CustomControl创建我自己的面板类型,因此我可以使我所有的面板看起来像一个带有背景,圆角等的框。

我没有遇到的麻烦是,我想在运行时更改使用TemplateBinding绑定的项的属性。

我的问题是通过代码改变这个不工作。

我希望有人能指出我的错误,告诉我我在哪里有点密集。

查找contentControl并更改其值,这只是永远不会出现在应用程序中,就好像绑定没有激活一样。

希望有人能帮忙。

控件模板。

<ControlTemplate x:Key="ContentBoxControlTemplate" TargetType="{x:Type local:ContentBox}"><Grid>
            <Grid.RowDefinitions>
                <RowDefinition Height="0.124*"/>
                <RowDefinition Height="0.876*"/>
            </Grid.RowDefinitions>
            <Border BorderBrush="Black" BorderThickness="0" HorizontalAlignment="Stretch" Height="Auto" VerticalAlignment="Stretch" CornerRadius="20" Grid.RowSpan="2" Style="{TemplateBinding Style}" />
            <Rectangle HorizontalAlignment="Stretch" Height="Auto" RadiusY="0" StrokeThickness="0" VerticalAlignment="Stretch" Width="Auto" Margin="10,0,10,20" Fill="White" Grid.Row="1"/>
            <Rectangle Fill="{DynamicResource TopInnerShadow}" HorizontalAlignment="Stretch" Height="Auto" RadiusY="0" StrokeThickness="0" VerticalAlignment="Stretch" Width="Auto" Margin="10,0,10,20" Grid.Row="1"/>
            <Rectangle Fill="{DynamicResource RightInnerShadow}" HorizontalAlignment="Stretch" Height="Auto" RadiusY="0" StrokeThickness="0" VerticalAlignment="Stretch" Width="Auto" Margin="10,0,10,20" Grid.Row="1"/>
            <TextBlock Grid.Row="0" x:Name="txtBoxHeading" HorizontalAlignment="Stretch" TextWrapping="Wrap" Text="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Title}" VerticalAlignment="Stretch" d:LayoutOverrides="Width, Height" Foreground="White" FontSize="36" FontFamily="Arial" Margin="20,5"/>
            <Grid Grid.Row="1">
                <ContentControl Content="{TemplateBinding Content}" Margin="10,0,10,20"/>
            </Grid>
        </Grid>
    </ControlTemplate>
继承自ContentControl 的strong>
public class ContentBox : ContentControl
{
    static ContentBox()
    {
        DefaultStyleKeyProperty.OverrideMetadata(typeof(ContentBox), new FrameworkPropertyMetadata(typeof(ContentBox)));
    }
    private string _title = "";
    public string Title
    {
        get { return _title; }
        set { _title = value; }
    }
    // Dependency Property
    public static DependencyProperty TitleProperty = DependencyProperty.Register("Title", typeof(string), typeof(ContentBox), new FrameworkPropertyMetadata("Title"));
}

使用内容控件的xaml

最后是修改属性

的代码
(this.Parent as ContentBox).Title = "Campaign: " + campaigns[0].Name;

WPF customcontroltemplate在运行时更新TemplateBinding

我发现我的错误,我是我认为,是愚蠢的!

在ContentControl中,我没有正确设置依赖属性。

将contentcontrol中的属性更改为以下内容修复了我的问题

public string Title
{
    get { return (string)this.GetValue(TitleProperty); }
    set { this.SetValue(TitleProperty, value); } 
}