如何将依赖属性绑定到Silverlight用户控件的UI?

Ken*_*hou 3 silverlight

我试图创建一个用户控件:

public partial class MyTextBlock : UserControl
  {
    public MyTextBlock()
      {
     InitializeComponent();
      }

     public static readonly DependencyProperty LabelProperty
      = DependencyProperty.RegisterAttached("Label", typeof(string), typeof(MyTextBlock), null);

     public string Label
        {
            get { return (string)GetValue(LabelProperty); }
            set { SetValue(LabelProperty, value); }
        }


     public static readonly DependencyProperty MyTextProperty
      = DependencyProperty.RegisterAttached("MyText", typeof(string), typeof(MyTextBlock), null);

     public string MyText
        {
            get { return (string)GetValue(MyTextProperty); }
            set { SetValue(MyTextProperty, value); }
        }
}
Run Code Online (Sandbox Code Playgroud)

它的xaml是:

<Grid x:Name="LayoutRoot">
   <TextBlock x:Name="Title"  Text="{Binding Label}" />
   <TextBlock x:Name="MyText" Text="{Binding MyText}" TextWrapping="Wrap"/>
</Grid>
Run Code Online (Sandbox Code Playgroud)

想要我想要尝试将此控件中的依赖属性绑定到UI元素,这样当我使用此控件时,我可以设置数据绑定,如:

 <local:MyTextBlock Label="{Binding ....}" MyText = "{Binding ....}" />
Run Code Online (Sandbox Code Playgroud)

但是,当我按照上面的方式行事时,它不起作用.没有数据绑定,没有错误.怎么解决?

Phi*_*gan 5

  • 尝试在DependencyProperty上使用.Register而不是.RegisterAttached
  • 您需要提供回调来设置值
  • 我认为'int'类型应该是'string'

把它们放在一起

public partial class MyTextBlock : UserControl
  {
    public MyTextBlock()
      {
     InitializeComponent();
      }

     public static readonly DependencyProperty LabelProperty
      = DependencyProperty.Register("Label", typeof(string), typeof(MyTextBlock), new PropertyMetadata(new PropertyChangedCallback(LabelChanged)));

     public string Label
        {
            get { return (string)GetValue(LabelProperty); }
            set { SetValue(LabelProperty, value); }
        }

       private static void LabelChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var c = d as MyTextBlock;
            if (c != null )
            {
                c.label.Text = e.NewValue as string;
            }
        }

}
Run Code Online (Sandbox Code Playgroud)

  • 接受的答案应该真的更新.手动设置Label属性是非常糟糕的做法. (2认同)