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

时间:2012-10-08 16:41:38

标签: c# wpf binding user-controls dependency-properties

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

我将此属性绑定到MainWindow中的DP(称为Test),它似乎每次更改时都会触发OnPropertyChanged个事件,但我的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>

2 个答案:

答案 0 :(得分:6)

问题是您要将ShowCategories值设置为自身:

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

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

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

答案 1 :(得分:1)

使绑定模式为TwoWay