【发布时间】:2018-04-14 04:01:47
【问题描述】:
我正在尝试了解 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中?
【问题讨论】:
-
您需要像msdn.microsoft.com/en-us/magazine/dn237302.aspx 中所述的命令来调用视图模型中的方法。
-
按钮有效(有点)。该方法被调用,但它不会更新 Textblock 的文本