我试图在MVVM环境中使用Binding更新TextBox的内容。当Button接收焦点时,它会传递一个值,该值应该反映在TextBox中。我似乎有第一部分正确,但似乎在努力传递价值.. 我知道有关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)));
}
}
然后我继续使用我的ViewModel:
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}"/>
然后我尝试从MainPage.cs更新Text
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;
}
如果有人能告诉我我做错了什么,我真的很感激。非常感谢提前。
答案 0 :(得分:1)
在MainPage构造函数中,尝试将datacontext设置为ViewModel。 有点像...
public MainPage()
{
InitializeComponent();
iText = new MainPageViewModel();
this.dataContext = iText;
}