WPF - 来自UserControl的属性更改通知

时间:2010-08-31 23:08:11

标签: wpf dependency-properties inotifypropertychanged

我有两个UserControls(uc1和uc2)加载到第三个UserControl(shell)。 Shell有两个属性,uc1和uc2,类型为UserControl1和UserControl2,每个属性都有一个DependencyProperty注册到它们自己的类IsDirty:

public static readonly DependencyProperty IsDirtyProperty = DependencyProperty.Register("IsDirty", typeof (bool), typeof (UserControl1));
public bool IsDirty
{
    get { return (bool) GetValue(IsDirtyProperty); }
    set { SetValue(IsDirtyProperty, value); }
}

(UserControl2的相同代码)

Shell 将TextBlocks绑定到IsDirty属性:

<TextBlock Text="{Binding ElementName=shell, Path=Uc1.IsDirty}"/>
<TextBlock Text="{Binding ElementName=shell, Path=Uc2.IsDirty}"/>

当我在uc1和uc2中更改IsDirty的值时,Shell永远不会得到通知。我错过了什么? UserControl是DependencyObject的后代......

如果我有通过INotifyPropertyChanged通知更改的常规属性,则会出现相同的行为。

如果我从uc1和uc2引发路由事件,冒泡到Shell,那么我可以捕获Dirty值,一切正常,但我不应该这样做,我应该吗?

由于

编辑:答案是在Uc1和Uc2属性上提升属性更改事件或使其成为DP。

2 个答案:

答案 0 :(得分:3)

我尝试使用简单的设置重现您的问题,它对我来说很好。我不确定这个设置是否足以复制你的情况。无论如何,我发布它以防万一。它可能会有所帮助:

XAML:

<Window x:Class="WpfApplication2.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfApplication2"
        x:Name="shell"
        Title="MainWindow" Height="350" Width="525">
    <StackPanel>
        <Button Click="Button_Click">Click</Button>
        <TextBlock Text="{Binding ElementName=shell, Path=Uc1.IsDirty}"/>
    </StackPanel>
</Window>

代码隐藏:

namespace WpfApplication2
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private MyUserControl uc1 = new MyUserControl();
        public MyUserControl Uc1
        {
            get { return this.uc1; }
        }

        public MainWindow()
        {
            InitializeComponent();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            this.uc1.IsDirty = !this.uc1.IsDirty;
        }


    }

    public partial class MyUserControl : UserControl
    {
        public MyUserControl()
        {
        }

        public bool IsDirty
        {
            get { return (bool)GetValue(IsDirtyProperty); }
            set { SetValue(IsDirtyProperty, value); }
        }

        // Using a DependencyProperty as the backing store for IsDirty.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty IsDirtyProperty =
            DependencyProperty.Register("IsDirty", typeof(bool), typeof(UserControl), new UIPropertyMetadata(false));

    }
}

答案 1 :(得分:1)

Karmicpuppet的答案很有效。但是它没有解决我的问题,因为Shell也是UserControl类型。为了它的工作,我需要提高在Uc1和Uc2上更改的属性。当我将它们声明为DependencyProperties时,它们都按预期工作。杜!