DependencyProperties未在UserControl中按预期触发回调

gen*_*nus 5 c# wpf binding user-controls dependency-properties

我有一个非常简单的例子,DependencyProperty我已经在UserControl上注册了,它没有按预期工作.

我将此属性绑定到MainWindow中的DP(称为Test),它似乎OnPropertyChanged每次更改时触发事件,但是DependencyProperty我的UserControl中作为此绑定的目标,似乎只在第一次通知此属性时才会收到通知改变.

这是我在代码中尝试做的事情:

我的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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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));
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

Jul*_*ain 6

问题是你要ShowCategories为自己设置值:

((UserControl1)d).ShowCategories = (bool)e.NewValue;
Run Code Online (Sandbox Code Playgroud)

这条线是没用的,因为ShowCategories已经修改了它的值.这就是为什么你首先在房产中改变了回调的原因.乍一看,这可以被视为无操作:毕竟,您只是将属性值设置为其当前值,这在WPF中不会引起任何更改.

但是,由于绑定不是双向的,因此更改属性值会覆盖绑定.这就是为什么不再提出回调的原因.只需删除回调中的分配即可.