2016-10-04 95 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))); 
     } 
    } 
}