【发布时间】:2020-05-02 19:45:16
【问题描述】:
我在我的WPF 项目中使用MVVMLight Toolkit。我所有的ViewModels 都派生自工具包的ViewModelBase 类,它为您实现INotifyPropertyChanged 并完成所有通知工作。
我当前的设置非常简单。我有一个带有单个 Name 属性的 Person 类。
public class Person
{
public string Name { get; set; }
}
我的窗口有一个TextBlock 和一个Button,并且我将Person 类对象的Name 属性绑定到我拥有的TextBlock。 DataContext 是使用 ViewModelLocator 类设置的。
<Window x:Class="BindingTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:ignore="http://www.galasoft.ch/ignore"
mc:Ignorable="d ignore"
Height="300" Width="300"
Title="MVVM Light Application"
DataContext="{Binding Main, Source={StaticResource Locator}}">
<Grid x:Name="LayoutRoot">
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<TextBlock Grid.Row="0" HorizontalAlignment="Center" VerticalAlignment="Center"
Text="{Binding Contact.Name}"/>
<Button Grid.Row="1" Content="Click" Command="{Binding ClickCommand}"/>
</Grid>
</Window>
在我的ViewModel 中,我在构造函数中将Name 设置为Tom,并在单击按钮时更改它。我希望Tom 在加载窗口时显示在TextBlock 中(它确实如此),并在单击按钮时更改为Jane(它没有)。
public class MainViewModel : ViewModelBase
{
private Person _contact = new Person();
public Person Contact
{
get { return _contact; }
set { Set(ref _contact, value); }
}
public RelayCommand ClickCommand { get; private set; }
public MainViewModel(IDataService dataService)
{
Contact = new Person() { Name = "Tom" };
ClickCommand = new RelayCommand(Click);
}
public void Click()
{
Contact.Name = "Jane";
}
}
我错过了什么?
【问题讨论】:
标签: c# wpf data-binding mvvm-light inotifypropertychanged