2012-10-08 10 views
4

매우 간단한 예제 인 DependencyProperty이 예상대로 작동하지 않는 UserControl에 등록했습니다.DependencyProperties는 UserControl에서 예상대로 콜백을 발생시키지 않습니다.

변경 될 때마다 OnPropertyChanged 이벤트가 발생하는 것으로 보이는 MainWindow의 DP (Test)에이 속성을 바인딩하고 있지만이 바인딩의 대상인 UserControl의 DependencyProperty 만 알림을받는 것으로 보입니다 이 속성이 처음 변경되었습니다.

내 UserControl을 :

public partial class UserControl1 : UserControl 
{ 
    public static readonly DependencyProperty ShowCategoriesProperty = 
     DependencyProperty.Register("ShowCategories", typeof(bool), typeof(UserControl1), new FrameworkPropertyMetadata(false, OnShowsCategoriesChanged)); 

    public UserControl1() 
    { 
     InitializeComponent(); 
    } 

    public bool ShowCategories 
    { 
     get 
     { 
      return (bool)GetValue(ShowCategoriesProperty); 
     } 
     set 
     { 
      SetValue(ShowCategoriesProperty, value); 
     } 
    } 

    private static void OnShowsCategoriesChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) 
    { 
     //this callback is only ever hit once when I expect 3 hits... 

     ((UserControl1)d).ShowCategories = (bool)e.NewValue; 
    } 
} 

MainWindow.xaml.cs를

public partial class MainWindow : Window, INotifyPropertyChanged 
{ 
    public MainWindow() 
    { 
     InitializeComponent(); 

     Test = true; //this call changes default value of our DP and OnShowsCategoriesChanged is called correctly in my UserControl 

     Test = false; //these following calls do nothing!! (here is where my issue is) 
     Test = true; 
    } 

    private bool test; 
    public bool Test 
    { 
     get { return test; } 
     set 
     { 
      test = value; 
      OnPropertyChanged("Test"); 
     } 
    } 

    public event PropertyChangedEventHandler PropertyChanged; 
    protected void OnPropertyChanged(string property) 
    { 
     PropertyChangedEventHandler handler = PropertyChanged; 
     if (handler != null) 
     { 
      handler(this, new PropertyChangedEventArgs(property)); 
     } 
    } 
} 

MainWindow.xaml

<Window x:Class="Binding.MainWindow" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:uc="clr-namespace:Binding" 
    DataContext="{Binding RelativeSource={RelativeSource Self}}"   
    Title="MainWindow" Height="350" Width="525"> 
    <Grid> 
    <uc:UserControl1 ShowCategories="{Binding Test}" /> 
    </Grid> 
</Window> 
다음

내가 코드에서 할 노력하고있어 것입니다

답변

6

문제는 당신은 그 자체로 ShowCategories 값을 설정하는 : ShowCategories의 값이 이미 수정 된 이후

((UserControl1)d).ShowCategories = (bool)e.NewValue; 

이 줄은, 쓸모가 없다. 그래서 처음에는 속성 콜백으로 변경되었습니다. 언뜻보기에 이는 아무 작업으로도 볼 수 있습니다. 결국 WPF에서는 속성 값을 현재 값으로 설정하기 만하면 WPF에서는 변경되지 않습니다.

그러나 바인딩이 양방향이 아니므로 속성 값을 변경하면 바인딩을 덮어 씁니다. 콜백이 더 이상 발생하지 않는 이유입니다. 콜백에서 과제를 삭제하기 만하면됩니다.

+0

멋진 캐치. 나는 심지어 콜백이하는 것에주의를 기울이지 않았다. –

+0

매우 명확한 설명에 감사드립니다! – genus

1

바인딩 모드를 TwoWay으로 설정하십시오.

+0

반쪽 만 – Firoso

관련 문제