Wpf数据绑定文本块未更新
我有一个简单的WPF窗口,带有一个滑块和两个文本块。滑块移动时,它会更新数据绑定对象。现在,第一个文本块更新,而第二个文本块不更新。为什么? 你可以说这里没有InotifyProperty更改。但为什么第一次更新?我的头发拉扯得够多了。请帮忙 我的WPF应用程序的所有荣耀如下Wpf数据绑定文本块未更新,wpf,Wpf,我有一个简单的WPF窗口,带有一个滑块和两个文本块。滑块移动时,它会更新数据绑定对象。现在,第一个文本块更新,而第二个文本块不更新。为什么? 你可以说这里没有InotifyProperty更改。但为什么第一次更新?我的头发拉扯得够多了。请帮忙 我的WPF应用程序的所有荣耀如下 <Window x:Class="DataTriggerDemo.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml
<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>
实际上,您遇到了WPF的另一个隐藏方面,即WPF的数据绑定引擎将数据绑定到PropertyDescriptor实例,如果源对象是普通CLR对象且未实现INotifyPropertyChanged接口,则该实例将封装源属性。数据绑定引擎将尝试通过PropertyDescriptor.AddValueChanged方法订阅属性更改事件。当目标数据绑定元素更改属性值时,数据绑定引擎将调用PropertyDescriptor.SetValue方法将更改后的值传递回源属性,同时引发ValueChanged事件通知此实例中的其他订户,其他订阅者将是列表框中的文本块
请参阅:可能是因为该值已从WPF更改,而该值已由您的代码更改两次。
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;
}
}
}
}