WinUI3:如何在视图模型中引用控件?

问题描述 投票:0回答:1
c# xaml uwp-xaml winui-3 winui
1个回答
2
投票

如错误消息所示,

MessageInput
控件不存在于*TestPageViewModel中。对于 MVVM,通常您应该使用绑定从视图中获取数据。

只是为了确保我们在同一页面上,在这种情况下:

  • TestPage.xaml 是 View
  • TestPage.xaml.cs 是 代码隐藏
  • TestPageViewModel.cs 是 ViewModel
  1. 安装 CommunityToolkit.Mvvm nuget 包。如果您使用 MVVM 模式,这将使您的生活更轻松。

  2. 在您的 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;
}
  1. 在您的代码隐藏中,TestPage.xaml.cs
public sealed partial class TestPage : Page
{
    public TestViewModel ViewModel { get; }

    public TestPage()
    {
        ViewModel = App.GetService<TestViewModel>();
        InitializeComponent();
    }
}
  1. 然后在您看来,TestPage.xaml
<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";
© www.soinside.com 2019 - 2024. All rights reserved.