当绑定到引用保持不变的对象时,忽略PropertyChanged

时间:2019-04-11 09:32:45

标签: c# wpf xaml data-binding

我对WPF /绑定世界还很陌生,但是现在我使用它已经有一段时间了,并且取得了一定程度的成功。

现在,我陷入了一个与this question中描述的问题非常相似的问题,但是问题是关于类而不是IEnumerable。我不确定这种行为是否也是故意的,或者是否有解决方法。

假设我有一个简单的自定义类“ Vector3”,其中包含3个双打 Vector3.cs

    public class Vector3
    {
        public double X { get; set; }
        public double Y { get; set; }
        public double Z { get; set; }

        public Vector3(double x, double y, double z)
        {
            X = x;
            Y = y;
            Z = z;
        }

        public Vector3(Vector3 vec)
        {
            X = vec.X;
            Y = vec.Y;
            Z = vec.Z;
        }

        public override bool Equals(object obj)
        {
            if (!(obj is Vector3))
                return false;

            Vector3 other = obj as Vector3;

            return X == other.X && Y == other.Y && Z == other.Z;
        }

        public override int GetHashCode()
        {
            unchecked
            {
                return (X.GetHashCode() * 42) ^ Y.GetHashCode() + Z.GetHashCode();
            }
        }
    }

我有一个用户控件,它公开了这种DependencyProperty

ucVector3.xaml.cs

public partial class ucVector3 : UserControl
    {
        public static readonly DependencyProperty ValueProperty = DependencyProperty.Register("Value",
                     typeof(Vector3), typeof(ucVector3),
                     new FrameworkPropertyMetadata(null, new PropertyChangedCallback(_OnModelChanged)));

        private static void _OnModelChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            Console.WriteLine("Binding worked! I've received a new Vector3 " +
                              "with value X = " + (e.NewValue as Vector3).X); 
        }

        public Vector3 Value
        {
            get
            {
                return (Vector3)GetValue(ValueProperty);
            }
            set
            {
                SetValue(ValueProperty, value);
            }
        }
    ...

然后,我尝试使用此用户控件绑定Value属性,如本例所示:

MainWindow.xaml

<Window x:Class="StackOverflow.Example.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:StackOverflow.Example"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Grid Background="Azure">
        <Grid.RowDefinitions>
            <RowDefinition Height="5*"/>
            <RowDefinition Height="1*"/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>
        <Button Content="Update" Margin="5" Grid.Row="1" Grid.ColumnSpan="2" Click="Button_Click" />
        <local:ucVector3 Value="{Binding SameReference}" Margin="5" />
        <local:ucVector3 Value="{Binding NewReference}" Margin="5" Grid.Column="1" />
    </Grid>
</Window>

MainWindow.xaml.cs

    public partial class MainWindow : Window, INotifyPropertyChanged
    {
        #region INotifyPropertyChanged
        SynchronizationContext uiContext = SynchronizationContext.Current;
        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            if (uiContext != SynchronizationContext.Current)
            {
                uiContext.Send(_ =>
                {
                    PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
                }, null);
            }
            else
            {
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
            }
        }
        #endregion

        private Vector3 newValue = new Vector3(0, 0, 0);

        public Vector3 SameReference { get; set; }
        public Vector3 NewReference { get; set; }

        public MainWindow()
        {
            this.DataContext = this;
            InitializeComponent();

        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            newValue.X = newValue.X + 2;
            newValue.Y = newValue.Y + 3;
            newValue.Z = newValue.Z + 4;

            SameReference = newValue;
            NewReference = new Vector3(newValue);

            OnPropertyChanged("SameReference"); //successful notify, ignored values
            OnPropertyChanged("NewReference"); //successful notify, processed values
        }
    }

第一次按下两个用户控件的按钮都将被(3,4,5)更新,但是从第二次开始,正确的用户控件中只有“ NewReference”属性将被更新。

我了解到,对于IEnumerables,WPF仅在引用不同的情况下才会传播OnPropertyChanged事件,并且IEnumerable中的更改需要改为调用INotifyCollectionChanged事件。

为什么我的“ OnPropertyChanged(“ SameReference”)”没有传播?我更改了值,希望事件传播以更新接口,否则我不会调用该事件...

此行为是故意的吗?为什么要检查对象引用,而不是检查是否等于?有办法“强迫”事件进行吗?还是在这种情况下我应该如何组织课程?

Here you can download the example solution described in this question,在VisualStudio2015中创建。

感谢您的宝贵时间。

1 个答案:

答案 0 :(得分:0)

从我在您的项目中看到的情况来看,您必须在ucVector3.xaml.cs中注释以下行,这些行避免更新用户控件:

        if (value.X == lastNudValue.X && value.Y == lastNudValue.Y && value.Z == lastNudValue.Z)
           return;