[英]Binding Textbox to Textblock via a Button, using ViewModels
我正在尝试了解 MVVM 的基础知识。
现在我有一个基本的 UWP 应用程序,我想在TextBox
输入文本,然后在按下Button
后在TextBlock
显示该文本。
如何使用 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>
MainPageViewModel: (C#)
public class MainPageViewModel : ViewModelBase
{
public MainPageViewModel()
{
}
public event PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
private string _OutPut;
public string OutPut
{
get
{
return _OutPut;
}
set
{
_OutPut = value;
RaisePropertyChanged(nameof(OutPut));
}
}
private string _FirstName;
public string FirstName
{
get
{
return _FirstName;
}
set
{
_FirstName = value;
RaisePropertyChanged(nameof(FirstName));
}
}
public void Add()
{
OutPut = FirstName;
// Debug.WriteLine(Output);
}
}
当我按下按钮时,输入文本会显示在输出窗口中,但是如何让它显示在Textblock
呢?
您的MainPageViewModel
或ViewModelBase
必须实现INotifyPropertyChanged
。 简单地添加PropertyChangedEventHandler
是不够的。
public class MainPageViewModel : ViewModelBase, INotifyPropertyChanged
或者
public class ViewModelBase : INotifyPropertyChanged
如果没有INotifyPropertyChanged
,您提供的代码(我在控件周围添加了一个StackPanel
因为页面只能有 1 个内容元素)在我的机器上不起作用,将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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.