c# - 虚拟机的 UWP MVVM 数据绑定(bind)(来自字符串的 textbox.text)

标签 c# mvvm data-binding uwp

好吧,尝试一下使用 UWP 模板 10 的 MVVM。我已经阅读了很多页面,尽管每个人都试图说它真的很简单,但我仍然无法让它工作。

将其置于上下文中,OCR 正在图像上运行,我希望文本自动显示在文本框中。

这是我的模型:

public class TextProcessing
{
    private string _ocrText;
    public string OcrText
    {
        get { return _ocrText; }
        set
        {
            _ocrText = value;
        }
    }
}

这是我的 View 模型:
public class ScanPageViewModel : ViewModelBase, INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    private TextProcessing _ocrTextVM;
    public ScanPageViewModel()
    {
        _ocrTextVM = new TextProcessing();
    }

    public TextProcessing OcrTextVM
    {
        get { return _ocrTextVM; }
        set {
            _ocrTextVM = value;
            this.OnPropertyChanged("OcrTextVM");
            }
    }

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

这是我的观点:
<TextBox x:Name="rtbOcr" 
       Text="{Binding OcrTextVM.OcrText, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" 

首先,这是行不通的。有人可以尝试显示我哪里出错了吗?

那么,数据来自服务文件,服务将如何更新值?什么是正确的代码?

提前致谢。

最佳答案

以下代码引用自 code.msdn ( How to achieve MVVM design patterns in UWP ),将对您有所帮助:

一步一步检查你的代码。

1.ViewModel实现接口(interface)INotifyPropertyChanged,并在属性设置方法中调用PropertyChanged,如下:

public sealed class MainPageViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    private string _productName;
    public string ProductName
    {
        get { return _productName; }
        set
        {
            _productName = value;
            if (PropertyChanged != null)
            {
                PropertyChanged.Invoke(this, new PropertyChangedEventArgs(nameof(ProductName)));
            }
        }
    }
}

2.在你的页面初始化你的ViewMode,并将DataContext设置为ViewMode,像这样:
public sealed partial class MainPage : Page
{
    public MainPageViewModel ViewModel { get; set; } = new MainPageViewModel();
    public MainPage()
    {
        ...
        this.DataContext = ViewModel;
    }
}

3.在你的xaml中,从viewMode绑定(bind)数据,像这样:
<TextBox Text="{Binding Path=ProductName,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" Name="ProductNameTextBox" TextChanged="ProductNameTextBox_TextChanged" />

关于c# - 虚拟机的 UWP MVVM 数据绑定(bind)(来自字符串的 textbox.text),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38949610/

相关文章:

c# - 我如何在 C# 中有条件地并行运行多个方法

wpf - Prism MVVM - 在 WPF 中的按钮单击命令上显示 View 模型中的弹出窗口

java - 我如何更新 ListItem (LiveData) 的字段

mvvm - avalondock mvvm

c# - 组合框显示命名空间.ViewModel

c# - 如何在 C# 库中使用嵌入式 .NET exe,而不从其 byte[] 重建文件?

c# - 转义 xml 中的特殊字符

c# - "Collection was modified..."问题

wpf - 通过样式在 TextBox 上设置 WPF Binding.StringFormat 属性

javascript - ReactJs:由于使用 Array.map,输入值不会改变