bmt*_*033 2 c# data-binding wpf xaml textblock
我正在更新一些现有的 WPF 代码,我的应用程序有许多这样定义的文本块:
<TextBlock x:Name="textBlockPropertyA"><Run Text="{Binding PropertyA}"/></TextBlock>
Run Code Online (Sandbox Code Playgroud)
在这种情况下,“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
}
}
Run Code Online (Sandbox Code Playgroud)
现在我有一个 TextBlock,我需要将它绑定到 ObjectA 的属性之一,如您所见,它是 MyBusinessObject 中的一个对象。在代码中,我将其称为:
MyBusinessObject.ObjectA.PropertyNameHere
Run Code Online (Sandbox Code Playgroud)
与我的其他绑定不同,“PropertyNameHere”不是 MyBusinessObject 的直接属性,而是 ObjectA 上的属性。我不确定如何在 XAML 文本块绑定中引用它。谁能告诉我我该怎么做?谢谢!
你可以简单地输入:
<TextBlock Text="{Binding ObjectA.PropertyNameHere"/>
Run Code Online (Sandbox Code Playgroud)
您可能希望INotifyPropertyChanged在您的ObjectA类中实现,因为PropertyChanged您的MyBusinessObject类中的方法不会获取类的更改属性。
在<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();
}
Run Code Online (Sandbox Code Playgroud)