매우 간단한 예제 인 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>
다음
내가 코드에서 할 노력하고있어 것입니다
멋진 캐치. 나는 심지어 콜백이하는 것에주의를 기울이지 않았다. –
매우 명확한 설명에 감사드립니다! – genus