基本上,我如何(单向)绑定到名为 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;
}
}
}