2017-10-18 69 views
0

我有一个简单的WPF窗口,带有滑块和两个文本块。随着滑块移动,它会更新数据绑定对象。现在第一个文本块更新,而第二个文本块不更新。为什么?Wpf Databound TextBlock不更新

你可以说这里没有INotifyPropertyChanged。但那为什么是第一次更新?我已经把我的头发拉得足够了。请帮忙。

我的WPF应用程序的所有荣耀如下。

<Window x:Class="DataTriggerDemo.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:DataTriggerDemo" 
      mc:Ignorable="d" 
      Title="MainWindow" Height="350" Width="525"> 
    <Grid> 
     <Grid.RowDefinitions> 
      <RowDefinition/> 
      <RowDefinition/> 
      <RowDefinition/> 
     </Grid.RowDefinitions> 

     <Slider x:Name="MySlider" Margin="5" Minimum="0" Maximum="100" 
        Value="{Binding TheValue}"/> 
     <TextBlock Grid.Row="1" Text="{Binding TheValue}" /> 
     <TextBlock Grid.Row="2" Text="{Binding TheValueTwice}" /> 
    </Grid> 
</Window> 

而现在代码背后。

using System.Windows; 
namespace DataTriggerDemo 
{ 
    public partial class MainWindow : Window 
    { 
     public MainWindow() 
     { 
      InitializeComponent(); 
      DataContext = new DataObject(); 
     } 
    } 

    public class DataObject 
    { 
     private int _theValue; 
     public int TheValue 
     { 
      get { return _theValue; } 
      set { 
       _theValue = value; 
       TheValueTwice = _theValue * 2; 
      } 
     } 
     private int _theValueTwice; 
     public int TheValueTwice 
     { 
      get { 
       return _theValueTwice; 
      } 
      set { 
       _theValueTwice = value; 
      } 
     } 
    } 
} 
+1

也许是因为TheValue从WPF改变,而TheValueTwice是由你的代码改变。 – Console

回答

1

其实你遇到一个WPF的另一个隐藏的方面,就是它WPF的数据绑定引擎将数据绑定到它包装源属性的PropertyDescriptor例如,如果源对象是一个普通的CLR对象,不执行INotifyPropertyChanged接口。数据绑定引擎将尝试通过PropertyDescriptor.AddValueChanged()方法来订阅属性已更改的事件。当目标数据绑定元素更改属性值时,数据绑定引擎将调用PropertyDescriptor.SetValue()方法将更改后的值传回给源属性,同时引发ValueChanged事件以通知其他订户(在此情况下,其他用户将是的TextBlocks列表框内

请参考:https://social.msdn.microsoft.com/Forums/vstudio/en-US/9365bb6a-b411-4967-9a03-ae2a810fb215/data-binding-without-inotifypropertychanged?forum=wpf