WPF中的依赖属性——我如何绑定到它

本文关键字:绑定 何绑定 依赖 属性 WPF | 更新日期: 2023-09-27 17:50:30

假设我在WPF UserControl中有以下代码:我想和Asset.ChildProperty结合。它目前不工作,因为我没有收到通知时,资产属性的变化。我如何安排事情,以便在AssetID更改时触发Asset属性的通知?

public static readonly DependencyProperty AssetIdProperty = DependencyProperty.Register("AssetId", typeof(string), typeof(GaugeBaseControl));
[Browsable(false), DataMember]
public string AssetId
{
    get { return (string)GetValue(AssetIdProperty); }
    set { SetValue(AssetIdProperty, value); }
}
[DisplayName("Asset Item"), Category("Value Binding")]
public AssetViewModel Asset
{
    get { return Manager.Models.FirstOrDefault(m => m.Model.UniqueId == AssetId); }
    set
    {
        if (value == null)
            AssetId = string.Empty;
        else
            AssetId = value.Model.UniqueId;
    }
}

WPF中的依赖属性——我如何绑定到它

您可以在DependencyPropertyPropertyMetadata中指定一个回调方法,当DependencyProperty的值发生变化时调用,并从该回调方法中引发PropertyChanged事件。

public class MyClass : DependencyObject, INotifyPropertyChanged
{
    public MyClass ()
    {
    }
    public event PropertyChangedEventHandler PropertyChanged;
    public bool State
    {
        get { return (bool)this.GetValue(StateProperty); }
        set { this.SetValue(StateProperty, value); } 
    }
    public static readonly DependencyProperty StateProperty =
        DependencyProperty.Register(
            "State", 
            typeof(bool), 
            typeof(MyClass),
            new PropertyMetadata(
                false, // Default value
                new PropertyChangedCallback(OnDependencyPropertyChange)));
    private static void OnDependencyPropertyChange(
        DependencyObject d, 
        DependencyPropertyChangedEventArgs e)
    {
        if (this.PropertyChanged != null)
        {
            this.PropertyChanged(d, 
                new PropertyChangedEventArgs(e.Property.Name);
        }
    }
}

如果你从State属性的setter中引发PropertyChanged事件,那么当属性被绑定时,它们将不会被触发,因为绑定直接调用StateProperty,而不是State

实现INotifyPropertyChanged并在Asset发生变化时引发PropertyChanged事件(在setter方法中)