c# - UWP:绑定(bind)到 View 模型属性

标签 c# mvvm uwp

在我的 View 模型中:

public string MyProperty{ get; set; }

public MyViewModel()
{
     MyProperty = "hello";
}

我已经定义了一个字符串属性。

现在,从我的页面,我想绑定(bind)到这个属性:
Text="{Binding MyProperty}"

但这不起作用 - 没有显示任何文字。我错过了什么?

编辑:
我的 View 模型继承自:
public class Observable : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        protected void Set<T>(ref T storage, T value, [CallerMemberName]string propertyName = null)
        {
            if (Equals(storage, value))
            {
                return;
            }

            storage = value;
            OnPropertyChanged(propertyName);
        }

        protected void OnPropertyChanged(string propertyName) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

编辑2:

我修改了我的 View 模型:
private string _myProperty;

        public string MyProperty
        {
            get => _myProperty;
            set => Set(ref _myProperty, value);
        }

        public MyViewModel()
        {
            _myProperty = "hello";
        }

和xml:
Text="{Binding MyProperty, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"

但它仍然无法正常工作。

编辑 3:我认为问题在于 Text property 是自定义控件的注册依赖属性:
public sealed partial class MyControl : UserControl
    {
        public MyControl()
        {
            InitializeComponent();
            DataContext = this;
        }

        public string Text
        {
            get => (string)GetValue(s_textProperty);
            set => SetValue(s_textProperty, value);
        }

        public static readonly DependencyProperty s_textProperty =
            DependencyProperty.Register("Text", typeof(string), typeof(MyControl), new PropertyMetadata(null));
    }

在控件的xaml中我有:
<TextBlock Text="{Binding Text}" />

这:
<MyControl Text="{Binding MyProperty}"/>

在我使用自定义控件的页面中。

最佳答案

你的类(class)应该实现INotifyPropertyChanged并拥有像这样的属性访问器:

public event PropertyChangedEventHandler PropertyChanged;

private string _myProperty;

public string MyProperty
{
    get { return _myProperty; }
    set
    {
        _myProperty = value;
        OnPropertyChanged();
    }
}

private void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
    PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}

在 XAML 中:
Text="{Binding MyProperty, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"

评论:

Mode = TwoWay - 如果被其中任何一个更改,属性将在 UI 和代码中同时更改。
UpdateSourceTrigger - 对 PropertyChanged 事件作出 react 。
另外,请阅读 DataContext :)

关于c# - UWP:绑定(bind)到 View 模型属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47925591/

相关文章:

c# - C#快速生成随机数

c# - 如何实现模型以强制客户端至少填写 ASP.NET MVC 中的两个输入之一

c# - WPF 导航和旋转背景

c# - Xamarin.Forms 如何将多个页面的 BindingContext 设置为同一个 ViewModel?

c# - Automapper:映射到 protected 属性(property)

c# - 渲染前获取 UserControl 的实际大小

WPF - 从数据获取超链接命令?

deployment - UWP 部署 Microsoft.NET.Native.Runtime.1.7 未找到错误

c# - FileOpenPicker 错误

Microsoft Band 2 上的 UWP