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

如何将依赖项属性绑定到silverlight用户控件的UI?,silverlight,Silverlight,我尝试将用户控件创建为: public partial class MyTextBlock : UserControl { public MyTextBlock() { InitializeComponent(); } public static readonly DependencyProperty LabelProperty = DependencyProperty.RegisterAttached("Label", ty

我尝试将用户控件创建为:

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); }
        }
}
其xaml是:

<Grid x:Name="LayoutRoot">
   <TextBlock x:Name="Title"  Text="{Binding Label}" />
   <TextBlock x:Name="MyText" Text="{Binding MyText}" TextWrapping="Wrap"/>
</Grid>

Want I Want尝试将此控件中的依赖项属性绑定到UI元素,以便在使用此控件时,可以设置如下数据绑定:

 <local:MyTextBlock Label="{Binding ....}" MyText = "{Binding ....}" />


但当我像上面那样做的时候,它不起作用了。没有数据绑定,没有错误。如何修复它?

基本上,您只需将这些依赖属性包装到一个类中。将控件上的
DataContext
设置为该类的实例并绑定。

  • 正在尝试使用.Register而不是.RegisterAttached依赖于DependencyProperty
  • 您需要提供一个回调来设置该值
  • 我认为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;
            }
        }

}

是,DataContext设置正确。如果我不使用控件MyTextBlock,只需直接使用系统TextBlock。很好,谢谢。int已更正为string。将尝试您的建议。+1使用
注册
注册
-1通过代码将label UI元素与label属性耦合会破坏使用依赖项属性的任何一点。只要
DataContext=this
,让绑定处理它。接受的答案应该真正更新。手动设置Label属性是非常糟糕的做法。