2013-01-03 3 views
1

WPF UserControl에 다음 코드가 있다고 가정합니다. Asset.ChildProperty에 바인딩하고 싶습니다. Asset 속성이 변경되면 알림을받지 않기 때문에 현재 작동하지 않습니다. AssetID가 변경 될 때마다 Asset 속성에 대한 알림이 트리거되도록 어떻게 정렬합니까?WPF의 종속 속성 - 어떻게 바인딩합니까?

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; 
    } 
} 

답변

1

INotifyPropertyChanged 구현하고 PropertyChanged 이벤트를 발생시킬 때 변화 Asset (세터 방법). 는 A DependencyProperty 변경의 가치와 그 콜백 메소드에서 PropertyChanged 이벤트를 발생시킬 때

+0

DependencyObject에서이를 구현하는 데 관심이 있습니까? – Brannon

+2

DependencyOjbect에서 해당 인터페이스를 구현할 필요가 없다는 점이 무엇입니까? – Brannon

+0

DependencyObject에서는 바인딩 대상으로 사용할 수있는 DependencyProperties를 정의 할 수 있습니다. 변경 알림 방법에서는 아무 것도하지 않습니다. 그걸 직접 추가해야합니다. 자세한 내용은 내 대답을 참조하십시오. –

2

당신은 DependencyPropertyPropertyMetadata에서 콜백 메서드를 호출 할 수 지정할 수 있습니다.

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가 직접 StateProperty을하지 호출하기 때문에 속성이 결합 할 때 발생하지 않습니다 State 재산의 세터에서 PropertyChanged 이벤트를 제기합니다.

관련 문제