C#通用应用程序-点击数据绑定

C#通用应用程序-点击数据绑定,c#,data-binding,win-universal-app,C#,Data Binding,Win Universal App,我在通用应用程序中的数据绑定方面遇到问题。以下是装订: <TextBlock x:Name="textBlockOutput" Text="{x:Bind ViewModel.textBlockValue, Mode=TwoWay}" /> 不幸的是,当我点击按钮时,textBlock的值没有被更新。当我调试应用程序时,我可以看到下面的函数被调用了,但它没有更改textBlock private void waitBtnClicked(object sender, RoutedEv

我在通用应用程序中的数据绑定方面遇到问题。以下是装订:

<TextBlock x:Name="textBlockOutput" Text="{x:Bind ViewModel.textBlockValue, Mode=TwoWay}" />
不幸的是,当我点击按钮时,textBlock的值没有被更新。当我调试应用程序时,我可以看到下面的函数被调用了,但它没有更改textBlock

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

有什么线索吗?

您需要指定视图可以观察到的属性。因此,必须从
INotifyPropertyChanged
INotifyPropertyChanging
接口实现ViewModel。然后按以下方式构建ViewModel类:

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自动更新。

您的解决方案可以正常工作,谢谢。尽管如此,我还是遇到了一些没有应用自动更新的示例,valyes已经更新-看起来是这样的:
不幸的是,我不知道如何将其应用于单个属性,而不是collections@PramusPL:这可能是因为集合是使用支持自动更新功能的
ObservableCollection
容器形成的。好的。对于更简单的属性有什么等价物吗?@PramusPL:这是处理简单属性的唯一方法。但如果您想简化这个过程,有一些VisualStudio插件可以自动化成员变量、属性、属性逻辑代码的创建过程。
<TextBlock x:Name="textBlockOutput" Text="{x:Bind ViewModel.TextBlockValue, Mode=TwoWay}" />