The standard property works, but the dependency property is missing in WPF

I have the following code that works:

public DataTemplate ItemTemplate { get { return _list.ItemTemplate; } set { _list.ItemTemplate = value; } } 

And I have the code that I want to have, but it does not work. Even a setter is never called:

 public static readonly DependencyProperty ItemTemplateProperty = DependencyProperty.Register("ItemTemplate", typeof(DataTemplate), typeof(MyUserControl)); public DataTemplate ItemTemplate { get { return (DataTemplate)GetValue(ItemTemplateProperty); } set { _list.ItemTemplate = value; SetValue(ItemTemplateProperty, value); } } 

Using this in XAML:

 <Window.Resources> <DataTemplate x:Key="ItemTemplate"> <TextBlock Text="{Binding Path=Name}"/> </DataTemplate> </Window.Resources> <local:MyUserControl ItemTemplate="{StaticResource ItemTemplate}"/> 

Why are there no standard property and dependency property?

+7
c # wpf xaml
source share
2 answers

The .Net dependency property does something not obvious: it accesses the dependency property identified by ItemTemplateProperty directly, instead of using the get and set methods that you declared. The only difference in this case is that your _list.ItemTemplate = value; never starts.

When you use dependency properties, your recipients and setters should contain only ordinary things . Everything else will be confusing because WPF goes around them when it uses a property.

If you need to set the value of _list.ItemTemplate to a value, you must add a static PropertyChangedCallback using another DependencyProperty.Register overload . For example.

 private static void OnItemTemplateChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var uc = (MyUserControl)d; uc._list.ItemTemplate = (DataTemplate)e.NewValue; } 
+7
source share

DependencyProperty never calls the Install method, instead you will have to look for the PropertyChanged event handler when creating the dependency property operator.

 public static readonly DependencyProperty ItemTemplateProperty = DependencyProperty.Register( "ItemTemplate", typeof(DataTemplate), typeof(MyUserControl), new FrameworkPropertyMetadata( null, new PropertyChangedCallback(ItemTemplateChanged) )); public DataTemplate ItemTemplate { get { return (DataTemplate)GetValue(ItemTemplateProperty); } set { _list.ItemTemplate = value; SetValue(ItemTemplateProperty, value); } } public static void ItemTemplateChanged( DependencyObject sender, DependencyPropertyChangedEventArgs e){ ((MyUserControl)sender).OnItemTemplateChanged(e); } protected void OnItemTemplateChanged(DependencyPropertyChangedEventArgs e){ // you write your code here.. } 
+2
source share

All Articles