开发者

WPF textblock binding question

开发者 https://www.devze.com 2022-12-30 18:16 出处:网络
I\'m trying to get my head around the whole MVVM thing and binding. I have a ViewModel class which has a property that is another class.I want to bind to a (string) property of that class to the text

I'm trying to get my head around the whole MVVM thing and binding. I have a ViewModel class which has a property that is another class. I want to bind to a (string) property of that class to the text of a textblock.

I set the ViewModel as my data context for my window\page. And then do this:

<TextBlock Text="{Binding ElementName=myAddressClass, Path=StreetName}" />

But this does not work. The text is empty.

I can expose the StreetName directly as below and this works:

<TextBlock Text="{Binding  Path=StreetName}" />

So am I doing something wrong in the first example. It seems simple enough ... am I just confuse about what an elementname is开发者_运维问答 or should be set to?

thanks


I think you probably are confused. If you want to bind to MyAddress.StreetName, just do this: Text="{Binding MyAddress.StreetName}" Make sure MyAddress is a property of your DataContext. ElementName is for binding to other controls.


ElementName is used to reference a XAML element in the Logical Tree. Since what you're trying to bind to is not an element, ElementName isn't the correct approach. Dotted path notation is the simplest approach in this case:

{Binding Path=myAddressClass.StreetName}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号