XAML 中的 WPF 文本块绑定
本文关键字:绑定 文本 WPF 中的 XAML | 更新日期: 2023-09-27 18:34:19
我正在更新一些现有的 WPF 代码,我的应用程序有许多文本块定义如下:
<TextBlock x:Name="textBlockPropertyA"><Run Text="{Binding PropertyA}"/></TextBlock>
在本例中,"PropertyA"是我的业务类对象的属性,定义如下:
public class MyBusinessObject : INotifyPropertyChanged
{
private void OnPropertyChanged(PropertyChangedEventArgs e)
{
if (PropertyChanged != null)
{
PropertyChanged(this, e);
}
}
private string _propertyA;
public string PropertyA
{
get { return _propertyA; }
set
{
if (_propertyA == value)
{
return;
}
_propertyA = value;
OnPropertyChanged(new PropertyChangedEventArgs("PropertyA"));
}
}
// my business object also contains another object like this
public SomeOtherObject ObjectA = new SomeOtherObject();
public MyBusinessObject()
{
// constructor
}
}
现在我有一个 TextBlock 我需要绑定到 ObjectA 的一个属性,正如你所看到的,它是 MyBusinessObject 中的一个对象。 在代码中,我将其称为:
MyBusinessObject.ObjectA.PropertyNameHere
与我的其他绑定不同,"PropertyNameHere"不是MyBusinessObject的直接属性,而是ObjectA上的属性。 我不确定如何在 XAML 文本块绑定中引用它。谁能告诉我我会怎么做? 谢谢!
在<Run Text="{Binding ObjectA.PropertyNameHere}" />
工作之前,您必须ObjectA
本身设置为属性,因为绑定仅适用于属性而不是字段。
// my business object also contains another object like this
public SomeOtherObject ObjectA { get; set; }
public MyBusinessObject()
{
// constructor
ObjectA = new SomeOtherObject();
}
您可以简单地键入以下内容:
<TextBlock Text="{Binding ObjectA.PropertyNameHere"/>
您可能希望在 ObjectA
类中实现INotifyPropertyChanged
,因为MyBusinessObject
类中的PropertyChanged
方法不会选取类的更改属性。
尝试以与对 PropertyA 相同的方式实例化 ObjectA(即作为属性,具有公共 getter/setter,并调用 OnPropertyChanged),则 XAML 可以是:
<TextBlock Text="{Binding ObjectA.PropertyNameHere}" />
您可以像对PropertyA
执行相同的操作,如下所示,
OnPropertyChanged(new PropertyChangedEventArgs("ObjectA"));
在设计器 XAML 上,
<TextBlock x:Name="ObjectAProperty" Text="{Binding ObjectA.PropertyNameHere}" />
试试这个:
在代码中:
public MyBusinessObject Instance { get; set; }
Instance = new MyBusinessObject();
在 XAML 中:
<TextBlock Text="{Binding Instance.PropertyNameHere" />