문제

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!

도움이 되었습니까?

해결책

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();
}

다른 팁

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.

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}" />

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}" />

Try this:

In code:

public MyBusinessObject Instance { get; set; }

Instance = new MyBusinessObject();

In XAML:

<TextBlock Text="{Binding Instance.PropertyNameHere" />
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top