开发者

How to bind dependency property to UI for silverlight user control?

开发者 https://www.devze.com 2022-12-13 09:05 出处:网络
I tried to create a user control as: public partial class MyTextBlock : UserControl { public MyTextBlock()

I tried to create a user control as:

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

     public static readonly DependencyProperty LabelProperty
      = DependencyProperty.Registe开发者_运维问答rAttached("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); }
        }
}

And its xaml is:

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

Want I want is trying to binding dependency property in this control to UI elements, so that when i use this control, I can set data binding like:

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

But When I did as above, it's not working. No data bound, no error. How to fix it?


  • Trying using .Register instead of .RegisterAttached on the DependencyProperty
  • You need to provide a callback to set the value
  • I think the 'int' type should be 'string'

putting it all together

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;
            }
        }

}


Basically you just have to wrap those dependency properties in a class. Set the DataContext on your control to an instance of that class and bind away.

0

精彩评论

暂无评论...
验证码 换一张
取 消