简体   繁体   中英

Dependency Property on a user control not updating the property when bound data changes

I've seen other have this issue on occasion and best I can tell I have duplicated several variations of their fixes but have not yet gotten this to work.

I know my bound data is sending proper INotify events because I can bind other controls to the data like textblocks and see its content change as the objects property changes, but my user control does not seem to be receiving the event at all.

public partial class MappingSelector : UserControl
{
    public Type OutputDriver
    {
        get { return (Type)GetValue(OutputDriverProperty); }
        set { Console.WriteLine(value.ToString()); SetValue(OutputDriverProperty, value); UpdateUI(); }
    }

    // Using a DependencyProperty as the backing store for OutPutDriver.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty OutputDriverProperty =
        DependencyProperty.Register("OutputDriver", typeof(Type), typeof(MappingSelector), new PropertyMetadata(null));
    public MappingSelector()
    {
        InitializeComponent();
        (this.Content as FrameworkElement).DataContext = this;
        //UpdateUI();
    }
}

The setter has a console trace that never fires so I am confident that the property is never being set.

I am then binding to it using:

<root:MappingSelector OutputDriver="{Binding LoadedProfile.UsedDriverInterface, ElementName=page, UpdateSourceTrigger=PropertyChanged}"/>

And I know LoadedProfile.UsedDriverInterface is updating and sending the proper events because I also have this which works just fine:

<TextBlock Text="{Binding LoadedProfile.UsedDriverInterface, ElementName=page, UpdateSourceTrigger=PropertyChanged}"/>

Late Edit: This works but is it really what I need to do? Is there no better way? Added this to the user control constructor;

        var OutputDriverDPD = DependencyPropertyDescriptor.FromProperty(OutputDriverProperty, typeof(MappingSelector));
        OutputDriverDPD.AddValueChanged(this, (sender, args) =>
        {
            OutputDriver = (Type)GetValue(OutputDriverProperty);
        });

The setter has a console trace that never fires so I am confident that the property is never being set.

This is a trap. The property getters and setters you have defined are for your convenience. The WPF Framework will not call them, it will use the dependency property directly. Never do anything in those getters and setters that you need to get done.

If you want to react to property changes, use the callback you already discovered. Your console trace should be in there, not in the setter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM