tags:

views:

102

answers:

2

I tried to create a user control as:

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

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?

A: 

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.

klausbyskov
Yes, DataContext is set correct. If I do not use control MyTextBlock, just use system TextBlock directly. it works fine.
KentZhou
A: 
  • 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;
            }
        }

}
Phillip Ngan
Thank you. int has been corrected to string. Will try your suggestion.
KentZhou
Thank you. your solution works perfectly.
KentZhou
+1 Use `Register` not `RegisterAttached`. -1 Coupling the label UI Element ot the Label property via code defeats any point in using a Dependency property. Just `DataContext = this` and let the binding take care of it.
AnthonyWJones