Reputation: 7250
I'm updating some existing WPF code and my application has a number of textblocks defined like this:
<TextBlock x:Name="textBlockPropertyA"><Run Text="{Binding PropertyA}"/></TextBlock>
In this case, "PropertyA" is a property of my business class object defined like this:
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
}
}
Now I have a TextBlock that I need to bind to one of the properties of ObjectA which, as you can see, is an object in MyBusinessObject. In code, I'd refer to this as:
MyBusinessObject.ObjectA.PropertyNameHere
Unlike my other bindings, "PropertyNameHere" isn't a direct property of MyBusinessObject but rather a property on ObjectA. I'm not sure how to reference this in a XAML textblock binding. Can anyone tell me how I'd do this? Thanks!
Upvotes: 3
Views: 33735
Reputation: 69985
Try this:
In code:
public MyBusinessObject Instance { get; set; }
Instance = new MyBusinessObject();
In XAML:
<TextBlock Text="{Binding Instance.PropertyNameHere" />
Upvotes: 1
Reputation: 17083
Before <Run Text="{Binding ObjectA.PropertyNameHere}" />
will work you have to make ObjectA
itself a property because binding will only work with properties not fields.
// my business object also contains another object like this
public SomeOtherObject ObjectA { get; set; }
public MyBusinessObject()
{
// constructor
ObjectA = new SomeOtherObject();
}
Upvotes: 6
Reputation: 26078
You can simply type this:
<TextBlock Text="{Binding ObjectA.PropertyNameHere"/>
You may want to implement INotifyPropertyChanged
within your ObjectA
class, as changing properties of the class will not be picked up by the PropertyChanged
methods in your MyBusinessObject
class.
Upvotes: 6
Reputation: 6490
You can do a same as you do for PropertyA
like follows,
OnPropertyChanged(new PropertyChangedEventArgs("ObjectA"));
on Designer XAML,
<TextBlock x:Name="ObjectAProperty" Text="{Binding ObjectA.PropertyNameHere}" />
Upvotes: 1
Reputation: 29963
Try to instantiate ObjectA in the same way as you are doing for PropertyA (Ie. as a property, with a public getter / setter, and calling OnPropertyChanged), then your XAML can be :
<TextBlock Text="{Binding ObjectA.PropertyNameHere}" />
Upvotes: 3