C# 通用应用程序 - 单击时的数据绑定

C# Universal App - Data binding on click

我在通用应用程序中遇到数据绑定问题。这是绑定:

<TextBlock x:Name="textBlockOutput" Text="{x:Bind ViewModel.textBlockValue, Mode=TwoWay}" />

当我初始化应用程序时,数据绑定工作得很好并且 textBlock 项目获得分配字段的值:

 public MainPage()
    {
        this.InitializeComponent();
        this.ViewModel = new MainViewModel();
        ViewModel.textBlockValue = "Click the button";
    }

不幸的是,当我点击按钮时,textBlock 的值没有被更新。当我调试应用程序时,我可以看到调用了下面的函数,但它没有对 textBlock 进行任何更改。

private void waitBtnClicked(object sender, RoutedEventArgs e)
{
    ViewModel.textBlockValue = "Clicked";
    SomeMethod();
}

有什么线索吗?

您需要指定 属性 以便 View 可以观察到。因此,您必须从 INotifyPropertyChangedINotifyPropertyChanging 接口实现您的 ViewModel。比构建你的 ViewModel class 如下:

class MainWindowViewModel : INotifyPropertyChanged, INotifyPropertyChanging
{
    private string textBlockValue;

    public string TextBlockValue
    {
        set
        {
            if (textBlockValue != value)
            {
                OnPropertyChanging("TextBlockValue");

                textBlockValue = value;

                OnPropertyChanged("TextBlockValue");
            }
        }
        get
        {
            return textBlockValue;
        }
    }
    ///////////////////////////////////////////////////////

    #region INotifyPropertyChanged Members

    public event PropertyChangedEventHandler PropertyChanged;

    #endregion

    #region INotifyPropertyChanging Members

    public event PropertyChangingEventHandler PropertyChanging;

    #endregion

    public void OnPropertyChanging(string propertyName)
    {
        if (PropertyChanging != null)
            PropertyChanging.Invoke(this, new PropertyChangingEventArgs(propertyName));
    }

    public void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
            PropertyChanged.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

比绑定到您的 XAML:

<TextBlock x:Name="textBlockOutput" Text="{x:Bind ViewModel.TextBlockValue, Mode=TwoWay}" />

因此您只需分配值抛出 属性 即可启用 UI 自动更新。