【问题标题】:WPF DataBinding: Bind to a property that references two other propertiesWPF DataBinding:绑定到引用其他两个属性的属性
【发布时间】:2010-07-20 19:15:50
【问题描述】:

基本上,我如何(单向)绑定到名为 txtFullName 的文本框。最初,文本框中的任何文本都会被清除/删除,因为 ToString 返回“”。但是,当我对 FirstName 或 LastName 进行更改时,它不会更新针对 FullName 的绑定。有什么办法吗?

另外,有没有办法绑定到一个方法(不仅仅是一个字段)?即直接将绑定设置为 ToString() 方法,并在 FirstName 或 LastName 更改时更新?

哦,如果有某种通用的方法来处理这个,那就太棒了……比如 FullName 字段上的一个属性或 ToString 方法上的一个属性,告诉它要查找哪些属性来进行更改。

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Text;
using System.Windows;
using System.Windows.Controls;

namespace AdvancedDataBinding
{
    public class UserEntity
    {
        static UserEntity()
        {
            FirstNameProperty = DependencyProperty.Register("FirstName", typeof(String), typeof(UserEntity));
            LastNameProperty = DependencyProperty.Register("LastName", typeof(String), typeof(UserEntity));
        }

        public String FirstName
        {
            get { return (String)GetValue(FirstNameProperty); }
            set { SetValue(FirstNameProperty, value); }
        }
        public static readonly DependencyProperty FirstNameProperty;

        public String LastName
        {
            get { return (String)GetValue(LastNameProperty); }
            set { SetValue(LastNameProperty, value); }
        }
        public static readonly DependencyProperty LastNameProperty;

        public String FullName
        {
            get { return ToString(); }
        }

        public override string ToString()
        {
            return FirstName + " " + LastName;
        }
    }
}

【问题讨论】:

    标签: wpf data-binding dependency-properties propertychanged


    【解决方案1】:

    如何将文本框绑定到多个值: 创建一个 MultiValueConverter 并使用它来绑定 FirstName 和 LastName。

    当 FirstName 或 LastName 更改时,FullName 不会通知。在您的类中,删除 DependencyProperty 的所有用法,而是让类实现 INotifyPropertyChanged。当 FirstName 或 LastName 更改时,为 FullName 发布 PropertyChanged 事件。将您的文本框直接绑定到 FullName。

    查看 ObjectDataProvider 以“绑定”到方法。

    在这些答案中,我建议你做第二个。

    【讨论】:

    • Man 即将发布关于 INotifyPropertyChanged 的​​相同内容。对于 3 小时前提出的问题,只有 6 次观看,我认为我在回答它时有一个表演...... ;)
    【解决方案2】:

    你可以像这样使用 MultiBinding...

    <TextBlock>
         <TextBlock.Text>
            <MultiBinding StringFormat="{}{0}, {1}">
               <Binding Path="LastName" />
               <Binding Path="FirstName" />
            </MultiBinding>
         </TextBlock.Text>
    </TextBlock>
    

    【讨论】:

      猜你喜欢
      • 2014-06-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-01
      相关资源
      最近更新 更多