假设我在WPF UserControl中有以下代码。我想绑定到Asset.ChildProperty
。它目前不起作用,因为我在Asset属性更改时没有收到通知。我如何安排事情,以便在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;
}
}
答案 0 :(得分:2)
当PropertyMetadata
的值更改并从该回调方法引发DependencyProperty
事件时,您可以在DependencyProperty
的{{1}}中指定一个回调方法
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);
}
}
}
属性的setter中引发PropertyChanged
个事件,那么当绑定属性时它们不会触发,因为绑定会直接调用State
,而不是StateProperty
。
答案 1 :(得分:1)
实施INotifyPropertyChanged
并在PropertyChanged
更改时(在setter方法中)提升Asset
事件。