【问题标题】:Wpf Databound TextBlock not updating [duplicate]Wpf数据绑定文本块不更新[重复]
【发布时间】:2017-10-18 05:08:31
【问题描述】:

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

你可能会说这里没有 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;
            }
        }
    }
}

【问题讨论】:

  • 可能是因为 TheValue 是从 WPF 更改的,而 TheValueTwice 是由您的代码更改的。

标签: wpf


【解决方案1】:

实际上,您遇到了 WPF 的另一个隐藏方面,那就是 WPF 的数据绑定引擎将数据绑定到 PropertyDescriptor 实例,如果源对象是普通 CLR 对象并且不实现 INotifyPropertyChanged 接口,则该实例包装源属性。并且数据绑定引擎将尝试通过 PropertyDescriptor.AddValueChanged() 方法订阅属性更改事件。而当目标数据绑定元素改变属性值时,数据绑定引擎会调用 PropertyDescriptor.SetValue() 方法将改变后的值传回源属性,同时会引发 ValueChanged 事件通知其他订阅者(在这种情况下,其他订阅者将是 ListBox 中的 TextBlock。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-14
    • 1970-01-01
    • 2023-03-23
    • 1970-01-01
    • 2011-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多