标签绑定不起作用

时间:2014-04-19 11:05:21

标签: c# wpf binding label

我正在尝试将标签绑定到Object.Object.Property,但我没有让它运行。

这是我的代码:

XAML

<Window x:Class="MyApp.MyWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MyWindow" Height="1120" Width="800">
    <Grid Name="MyGrid">
        <StackPanel Orientation="Horizontal">
            <Label FontWeight="Bold" FontSize="40" Content="{Binding MyDataObject/AnotherSubObject/MyProperty}"/>
        </StackPanel>
    </Grid>
</Window>

代码

public partial class MyWindow : Window
{
    public MySubObject MyDataObject { get; set; }

    public MyWindow(MySubObject object)
    {
        InitializeComponent();

        this.MyDataObject = object; // Contains MyDataObject.AnotherObject.MyProperty

        DataContext = this;
    }
}

MySubObject 对象的代码如下所示:

    public class MySubObject : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    AnotherObject _AnotherObject;

    public MySubObject()
    {
        this._AnotherObject = new AnotherObject();
        this._AnotherObject.Property = "Some Value";
    }

    public AnotherObject AnotherObject
    {
        get { return _AnotherObject; }
        set { _AnotherObject = value; OnPropertyChanged("AnotherObject"); }
    }

    // Create the OnPropertyChanged method to raise the event
    protected void OnPropertyChanged(string name)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(name));
        }
    }
}

我很高兴得到这个案件的圆顶支持。

1 个答案:

答案 0 :(得分:1)

使用 Dot(.) 作为绑定属性路径分隔符 Forward slash(/)

<Label FontWeight="Bold" FontSize="40"
       Content="{Binding MyDataObject.AnotherSubObject.MyProperty}"/>