如错误消息所示,
MessageInput
控件不存在于*TestPageViewModel中。对于 MVVM,通常您应该使用绑定从视图中获取数据。
只是为了确保我们在同一页面上,在这种情况下:
安装 CommunityToolkit.Mvvm nuget 包。如果您使用 MVVM 模式,这将使您的生活更轻松。
在您的 ViewModel 中,TestPageViewModel:
// This class needs to be "partial"
// for the "CommunityToolkit.Mvvm" source generators.
public partial class TestPageViewModel : ObservableObject
{
// The source generators will create
// an UI interactable "SomeText" property for you.
[ObservableProperty]
private string someText;
}
public sealed partial class TestPage : Page
{
public TestViewModel ViewModel { get; }
public TestPage()
{
ViewModel = App.GetService<TestViewModel>();
InitializeComponent();
}
}
<TextBox
x:Name="MessageInput"
Text="{x:Bind ViewModel.SomeText, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
仅此而已。每次您更改 TextBox
中的文本时,
SomeText都会更新。
顺便说一句,您可以直接从代码隐藏访问
TextBox
。只要确保使用 x:Name
来命名即可。
TestPage.xaml.cs
MessageInput.Text = "some text";