How do I associate a dependency property with a user interface for a Silverlight user control?

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 his xaml:

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

I want to try to bind the dependency property in this control to the user interface elements, so when I use this control, I can set the data binding, for example:

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

But when I did the same as above, it does not work. No data, no errors. How to fix it?

+3
source share
2 answers
  • Trying to use .Register instead of .RegisterAttached on DependencyProperty
  • You need to specify a callback to set the value
  • , '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;
            }
        }

}
+5

. DataContext .

0

Source: https://habr.com/ru/post/1725072/


All Articles