I am trying to understand the basics of MVVM.
Now I have a basic UWP app where I want to input a text in a TextBox
, then display that text in a TextBlock
, after I press a Button
.
How can I do this using 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);
}
}
When I press the button, the input text is displayed in the output window, but how can I get it to be displayed in the Textblock
?
Your MainPageViewModel
or ViewModelBase
has to implement INotifyPropertyChanged
. Simply adding the PropertyChangedEventHandler
is not enough.
public class MainPageViewModel : ViewModelBase, INotifyPropertyChanged
or
public class ViewModelBase : INotifyPropertyChanged
Without INotifyPropertyChanged
, your provided code (I added a StackPanel
around the controls as the Page can only have 1 content element) does not work on my machine, with INotifyPropertyChanged
added to the code, it works.
Bonus: if you want to use x:Bind
for all your bindings, you'll have to set Mode=OneWay
on the TextBlock
binding, as the default for x:Bind
is 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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.