Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF textblock binding in XAML

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!

like image 975
bmt22033 Avatar asked Jun 04 '26 03:06

bmt22033


1 Answers

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();
}
like image 132
LPL Avatar answered Jun 06 '26 16:06

LPL



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!