2016-10-04 98 views
1

我在ViewModel中有两个公共属性FooBarFoo只是一个字符串,Bar是一个具有公共属性Name的类,它是一个字符串。在DataBinding中访问属性的属性

我想将Bar.Name绑定到某个GUI元素。 我该怎么做?

<Label Content="{Binding Foo}">按预期将字符串Foo写入标签。

<Label Content="{Binding Bar.Name}">不会将名称Bar写入标签。相反,标签保持空白。

编辑: 我的XAML的DataContext(因此,标签)设置为ViewModel。

编辑2:当然,真正的代码并不像上面描述的那么简单。我建了一个最小的工作示例,仅表示上面的描述:

XAML:

<Window x:Class="MyTestNamespace.MyXAML" 
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"> 
    <StackPanel> 
     <Label Content="{Binding Foo}"></Label> 
     <Label Content="{Binding Bar.Name}"></Label> <!-- Works fine! --> 
    </StackPanel> 
</Window> 

视图模型:

namespace MyTestNamespace 
{ 
    class MyVM 
    { 
     public string Foo { get; set; } 
     public MyBar Bar { get; set; } 

     public MyVM() 
     { 
      Foo = "I am Foo."; 
      Bar = new MyBar("I am Bar's name."); 
     } 
    } 

    class MyBar 
    { 
     public string Name { get; set; } 

     public MyBar(string text) 
     { 
      Name = text; 
     } 
    } 
} 

这实际上确实工作正常。由于我无法与您分享实际的代码(太多并由公司所有),因此我需要自行寻找原因。欢迎提供任何可能的原因提示!

+0

您确保酒吧类的实例在您的视图模型的名称属性被填充(和酒吧属性正确实例)? DataContext是如何在你的标签(或其中一个父类或DataTemplate)上设置的? –

+0

是的,一切都设置正确。我可以使用代码中的Bar.Name来正常工作。 “Bar”和“Bar.Name”都不为null。 – Kjara

+0

请分享代码以获取更多信息 –

回答

0

贵国Model.cs:

public class Model : INotifyPropertyChanged 
{ 
    private string _name; 
    public string Name 
    { 
     get { return _name; } 
     set 
     { 
      _name = value; 
      PropertyChanged(this, new PropertyChangedEventArgs("Name")); 
     } 
    } 
    public event PropertyChangedEventHandler PropertyChanged = delegate { }; 
} 

2.您的视图模型:

public MainViewModel() 
    { 
    _model = new Model {Name = "Prop Name" }; 
    } 



    private Model _model; 
    public Model Model 
    { 
     get 
     { 
      return _model; 
     } 
     set 
     { 
      _model = value;  
     } 
    } 

3.您查看,与DataContext的设置为您的视图模型:

<Window x:Class="WpfApplication1.MainWindow" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
    mc:Ignorable="d" 
    Title="MainWindow" 
    DataContext="{StaticResource MainViewModel}"> 
<Grid> 
    <Label Content="{Binding Model.Name}"/> 
</Grid> 

0

感谢Vignesh N.的评论我能够解决这个问题。

在实际的代码Bar可以改变,但在开始它的名字是一个空字符串。这是标签在窗口打开时显示的内容。由于LabelBar属性更改时未收到通知,因此它不会更新。

解决办法:视图模型实现INotifyPropertyChanged接口和定义Bar这样的:

private MyBar _bar; 
public MyBar Bar 
{ 
    get 
    { 
     return _bar; 
    } 

    set 
    { 
     if (_bar != value) 
     { 
      _bar = value; 
      PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Bar))); 
     } 
    } 
}