我正在尝试在MVVM环境中使用绑定更新文本框的内容。当按钮接收焦点时,它会传递一个值,该值应反映在文本框中。我似乎对了第一部分,但是似乎正在努力传递价值。我知道之前已经问过关于MVVM的问题(包括我自己(,但由于某些原因,我真的无法理解。
所以我从我的模型开始:
public class iText : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private string _text;
public string Text
{
get { return _text; }
set
{
_text = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Text)));
}
}
然后,我继续使用我的视图模型:
private iText _helper = new iText();
public iText Helper
{
get { return _helper; }
set
{
_helper = value;
}
}
XAML 页:
<Page.Resources>
<scan:ModelDataContext x:Key="ModelDataContext" x:Name="ModelDataContext"/>
</Page.Resources>
<TextBox Text="{Binding Helper.Text, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
然后,我尝试从主页更新文本.cs
public sealed partial class MainPage : Page
{
public MainPageViewModel iText { get; set; }
public MainPage()
{
InitializeComponent();
iText = new MainPageViewModel();
}
private void btn_GotFocus(object sender, RoutedEventArgs e)
{
var str = "test"
iText.Helper.Text = str;
}
如果有人能告诉我我做错了什么,在哪里做错了,我真的很感激。提前非常感谢。
在 MainPage 构造函数中,尝试将数据上下文设置为 ViewModel。像...
public MainPage()
{
InitializeComponent();
iText = new MainPageViewModel();
this.dataContext = iText;
}