C# 使用ViewModels通过按钮将Textbox绑定到Textblock

C# 使用ViewModels通过按钮将Textbox绑定到Textblock,c#,.net,mvvm,binding,uwp,C#,.net,Mvvm,Binding,Uwp,我正在努力理解MVVM的基础知识 现在我有了一个基本的UWP应用程序,我想在文本框中输入一个文本,然后在按下按钮后在文本块中显示该文本 如何使用MVVM实现这一点 XAML <Page.DataContext> <vm:MainPageViewModel x:Name="ViewModel" /> </Page.DataContext> <StackPanel> <TextBox Width="200" Height="40

我正在努力理解MVVM的基础知识

现在我有了一个基本的UWP应用程序,我想在
文本框
中输入一个文本,然后在按下
按钮后在
文本块
中显示该文本

如何使用MVVM实现这一点

XAML

<Page.DataContext>
    <vm:MainPageViewModel x:Name="ViewModel" />
</Page.DataContext>

<StackPanel>
    <TextBox Width="200" Height="40" Text="{Binding FirstName, Mode=TwoWay}" ></TextBox>
    <Button  Content="Add" Click="{x:Bind ViewModel.Add}" ></Button>
    <TextBlock FontSize="30" Text="{Binding OutPut}" ></TextBlock>
</StackPanel>

当我按下按钮时,输入文本将显示在输出窗口中,但如何使其显示在
Textblock
中?

您的
MainPageViewModel
ViewModelBase
必须实现
INotifyPropertyChanged
。仅仅添加
属性changedeventhandler
是不够的

public class MainPageViewModel : ViewModelBase, INotifyPropertyChanged

如果没有
INotifyPropertyChanged
,您提供的代码(我在控件周围添加了一个
StackPanel
,因为页面只能有一个内容元素)在我的机器上不起作用,如果将
INotifyPropertyChanged
添加到代码中,它就起作用了


额外好处:如果您想对所有绑定使用
x:Bind
,您必须在
TextBlock
绑定上设置
Mode=OneWay
,因为
x:Bind
的默认值是
OneTime

<Page.DataContext>
    <local:MainViewModel x:Name="ViewModel" />
</Page.DataContext>

<StackPanel>
    <TextBox Width="200" Height="40" Text="{x:Bind ViewModel.FirstName, Mode=TwoWay}" ></TextBox>
    <Button  Content="Add" Click="{x:Bind ViewModel.Add}" ></Button>
    <TextBlock FontSize="30" Text="{x:Bind ViewModel.OutPut, Mode=OneWay}" ></TextBlock>
</StackPanel>


您需要一个如中所述的命令来调用视图模型中的方法。该方法已被调用,但不会更新Textblock的文本。我有一个简短的问题要问你。在使用模板10 Nuget时,我在MainPageViewModel中扩展了ViewModelBase,它扩展了BindableBase,BindableBase再次实现了INotifyPropertyChanged。为什么我需要再次实现INotifyPropertyChanged,而它是实现该接口的类的子类?您正在重新定义事件处理程序,从而将其隐藏在BindableBase(多态性)中。如果您使用的是Template10,那么应该在属性设置器中使用。
public class ViewModelBase : INotifyPropertyChanged
<Page.DataContext>
    <local:MainViewModel x:Name="ViewModel" />
</Page.DataContext>

<StackPanel>
    <TextBox Width="200" Height="40" Text="{x:Bind ViewModel.FirstName, Mode=TwoWay}" ></TextBox>
    <Button  Content="Add" Click="{x:Bind ViewModel.Add}" ></Button>
    <TextBlock FontSize="30" Text="{x:Bind ViewModel.OutPut, Mode=OneWay}" ></TextBlock>
</StackPanel>