代码之家  ›  专栏  ›  技术社区  ›  Jake

依赖属性绑定未更新目标

  •  1
  • Jake  · 技术社区  · 14 年前

    我有一个自定义依赖属性:

        public static readonly DependencyProperty HeaderProperty = DependencyProperty.Register("HeaderProperty", typeof(string), typeof(RadAdjustableSlider));
        public string Header
        {
            get
            {
                return (string)GetValue(HeaderProperty);
            }
            set
            {
                SetValue(HeaderProperty, value);
            }
        }
    

    <TextBlock Name="txtHeader" Text="{Binding ElementName=main, Path=Header, UpdateSourceTrigger=PropertyChanged, Mode=OneWay}" />
    

    请注意,我在xaml文件顶部的声明中也有以下内容:

             x:Name="main"
    

        public RadAdjustableSlider()
        {
            InitializeComponent();
            this.Header = "Header";
        }
    

    当我将此控件放在另一个父控件中时,标题textblock为空。为什么?

    编辑: This blog ValidateValueCallback DependencyProperty.Register

    2 回复  |  直到 14 年前
        1
  •  1
  •   justin.m.chase    14 年前

    框架中已经有HeaderedContentControl和headeredItemControl。。。

    但是如果您真的想创建自己的模板,那么您可能应该使用TemplateBinding。请尝试以下操作:

    class MyHeaderedControl : ContentControl
    {
      public static readonly DependencyProperty HeaderProperty = DependencyProperty.Register(
        "Header",
        typeof(object),
        typeof(MyHeaderedControl),
        new PropertyMetadata());
    
      public MyHeaderedControl()
      {
        this.DefaultStyleKey = typeof(MyHeaderedControl);
      }
    }
    

    <ResourceDictionary
      xmlns="..."
      xmlns:x="..."
      xmlns:c="MyControlLibrary1"
      >
      <Style TargetType="{x:Type c:MyHeaderedControl>
        <Setter Property="Template">
          <Setter.Value>
            <ControlTemplate TargetType="{x:Type c:MyHeaderedControl}">
              <StackPanel>
                <ContentControl Content="{TemplateBinding Header}" />
                <ContentPresenter /> 
              </StackPanel>
            </ControlTemplate>
          </Setter.Value>
        </Setter>
      </Style>
    </ResourceDictionary>
    

    此外,在AssemblyInfo.cs中,如果尚未添加此属性,请添加该属性:

    [assembly: ThemeInfo(ResourceDictionaryLocation.SourceAssembly, 
           ResourceDictionaryLocation.SourceAssembly)]
    

    所以我们来做一个概述。一般的想法是创建某种类型的逻辑控件,其中包含属性、事件和逻辑等,然后在同一个程序集中提供默认主题。这就是默认情况下控件的显示方式。在使用控件的任何地方,都可以覆盖默认模板,并且可以像往常一样覆盖特定模板。

        2
  •  0
  •   Andrew Jackson    13 年前

    正如justin.m.chase上面提到的,自定义控件可能是最好的方法,但是UserControls是一个常见的场景,所以我还是要添加我的2c。

    要更改此行为,请在usercontrol构造函数中设置DataContext属性:

    public RadAdjustableSlider()
    {
        InitializeComponent();
        this.Header = "Header";
    
        this.DataContext = this;
    }
    

    <TextBlock Text="{Binding Header}" />
    

    <TextBlock Text="{Binding Header, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type ns:RadAdjustableSlider}}}" />