我在ViewModel中有兩個公共屬性Foo
和Bar
。 Foo
只是一個字符串,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;
}
}
}
這實際上確實工作正常。由於我無法與您分享實際的代碼(太多並由公司所有),因此我需要自行尋找原因。歡迎提供任何可能的原因提示!
您確保酒吧類的實例在您的視圖模型的名稱屬性被填充(和酒吧屬性正確實例)? DataContext是如何在你的標籤(或其中一個父類或DataTemplate)上設置的? –
是的,一切都設置正確。我可以使用代碼中的Bar.Name來正常工作。 「Bar」和「Bar.Name」都不爲null。 – Kjara
請分享代碼以獲取更多信息 –