简体   繁体   English

您如何绑定到类属性?

[英]How do you bind to a class property?

Is it possible to bind to the property inside a class? 是否可以绑定到类内的属性?

Say I have in my ViewModel a property like this (my ViewModel inherits from BindableBase) 假设我在ViewModel中具有这样的属性(我的ViewModel继承自BindableBase)

    private PointOfView _userPointOfView;
    public PointOfView UserPointOfView
    {
        get { return _userPointOfView; }
        set{ SetProperty(ref _userPointOfView, value); }
    }

Where PointOfView class has some property say a string variable called 'UserString' 如果PointOfView类具有某些属性,则说一个名为“ UserString”的字符串变量

And in my application I'm setting my datacontext like this 在我的应用程序中,我像这样设置数据上下文

    public MainPage()
    {
        this.InitializeComponent();
        DataContext = App.ViewModel;


        PointOfView POV = bew PointOfView();
        POV.UserString = "Test";
        App.ViewModel.UserPointOfView = POV;

    }

What I want to do in my XAML is something like 我想在XAML中执行的操作类似于

<TextBlock Text="{Binding UserPointOfView.UserString, Mode="OneWay"}"></TextBlock>

Anyway I tried something like that but it never update the textblock on the xaml page. 无论如何,我尝试过类似的方法,但是它从未更新过xaml页面上的textblock。

Does anyone know if there is a way to do this? 有谁知道有没有办法做到这一点? It would be some much easier and save a lot of code duplication in my ViewModel, instead of creating so many properties for every property inside the class. 这样会容易得多,并且可以在ViewModel中节省大量代码重复,而不是为类中的每个属性创建这么多属性。

It is possible, and very common to bind to a 'nested' property. 绑定到“嵌套”属性是可能的,而且很常见。 If your bound values are not appearing, then you may not have the DataContext set correctly. 如果没有出现绑定值,则可能没有正确设置DataContext。 Use the debug output window for a hint as to what is not binding correctly. 使用调试输出窗口可以提示未正确绑定的内容。

Also, if your PointOfView class does not implement INotifyPropertyChanged, then your binding won't automatically update. 另外,如果PointOfView类未实现INotifyPropertyChanged,则绑定将不会自动更新。 It will only display the value as it first appeared when the binding was established. 它只会显示建立绑定时首次出现的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM