好吧,尝试一下使用 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/