【问题标题】:Another WPF Binding Syntax Question另一个 WPF 绑定语法问题
【发布时间】:2011-06-14 01:43:12
【问题描述】:

这次我的测试代码显示了一个文本框和两个文本块。 TextBox 和第一个 TextBlock 通过双向数据绑定连接到数据上下文的字符串属性。第二个 TextBlock 由 TextBox 的 TextChanged 事件上的事件处理程序更新,将其设置为字符串属性的当前值。

当窗口加载时,两个 TextBlock 都被正确初始化。但是当我输入文本框时,只有第二个更新。第二个 TextBlock 已更新的事实证实了 TextBox 到字符串属性的双向绑定是有效的。但是为什么第一个 TextBlock 没有更新呢?

标记:

<Window x:Class="DataBinding.SimpleDataBinding"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="SimpleDataBinding" Height="300" Width="300" >
    <StackPanel>
        <TextBox Name="txtPerson" Text="{Binding Path=Person, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
        <TextBlock Name="tbPerson1" Text="{Binding Path=Person, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
        <TextBlock Name="tbPerson2" />
    </StackPanel>
</Window>

后面的代码:

using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;

namespace DataBinding
{
    public partial class SimpleDataBinding : Window
    {
        public string Person { get; set; }

        public SimpleDataBinding() {
             InitializeComponent();
             Person = "George";
             DataContext = this;
             txtPerson.TextChanged += new TextChangedEventHandler(txtPerson_TextChanged);
        }

        private void txtPerson_TextChanged(object sender, TextChangedEventArgs e) {
            tbPerson2.Text = Person;
        }
    }
}

【问题讨论】:

  • The manual,你应该阅读它。
  • "要使 TwoWay 和 OneWayToSource 绑定起作用,源对象需要提供属性更改通知。"正确的例子在How to: Implement Property Change Notification
  • 我不是想“举个例子”。您应该阅读包含该部分的完整手册。您肯定会遇到其他问题,其中绝大多数都在此处进行了解释,如果您不阅读它,您最终会不必要地在这里提问。

标签: wpf binding


【解决方案1】:

您的第二个文本框没有通过数据绑定更新——它正在更新,因为您直接在事件处理程序中更改了它的值。

您背后的代码需要实现接口 INotifyPropertyChanged。这个接口和实现是数据绑定的关键,如果你正在学习 WPF/Silverlight 并想使用数据绑定,你需要了解所有关于这个接口以及如何实现它。

INotifyPropertyChanged

这是一个基本的实现(来自上面的链接):

public event PropertyChangedEventHandler PropertyChanged;

private void NotifyPropertyChanged(String info)
{
    if (PropertyChanged != null)
    {
        PropertyChanged(this, new PropertyChangedEventArgs(info));
    }
}

以下是您希望在示例中使用它的方式(未经测试且未输入到 IDE,因此可能会出现错误):

private string _person;
public string Person 
{ 
    get {return _person;}
    set 
    {
        if (value == _person) return;
        _person = value;
        NotifyPropertyChanged("Person");
    }
}

那你就可以去掉这行了:

txtPerson.TextChanged += new TextChangedEventHandler(txtPerson_TextChanged);

并将绑定添加到您的第二个文本块:

<TextBlock Name="tbPerson2" Text="{Binding Path=Person, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />

您也可以从文本框和文本块中删除名称,因为在使用数据绑定时几乎不需要名称。

【讨论】:

    猜你喜欢
    • 2011-01-30
    • 1970-01-01
    • 2020-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-18
    • 2010-12-09
    相关资源
    最近更新 更多