Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DependencyProperty not triggered

I defined property in my usercontrol like this:

 public bool IsSelected 
 {
     get { return (bool)GetValue(IsSelectedProperty); }
     set
     {
         SetValue(IsSelectedProperty, value);
         StackPanelDetails.Visibility = value ? Visibility.Visible : Visibility.Collapsed;
     }
 }

 public static readonly DependencyProperty IsSelectedProperty =
        DependencyProperty.Register("IsSelected", typeof (bool), typeof (ucMyControl));

But when I set its property in xaml, it want trigger it (set is not called).

 <DataTemplate><local:ucTopicItem IsSelected="False" /></DataTemplate>

What could be the problem?

like image 412
Nickolodeon Avatar asked Feb 09 '12 14:02

Nickolodeon


2 Answers

The setter of your dependency property will not be called when the property is set in XAML. WPF will instead call the SetValue method directly.

See MSDN XAML Loading and Dependency Properties for an explanation why the setter is not called.

You would have to register a PropertyChangedCallback with property metadata.

like image 137
Clemens Avatar answered Nov 17 '22 20:11

Clemens


You should use a property changed handler in your dependency property directly. This way you ensure that it gets called when set in XAML:

public static readonly DependencyProperty IsSelectedProperty =
    DependencyProperty.Register("IsSelected", typeof(bool), typeof(ucMyControl), new PropertyMetadata(false, OnIsSelectedChanged));

private static void OnIsSelectedChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    // Implement change logic
}
like image 33
jjrdk Avatar answered Nov 17 '22 19:11

jjrdk