我有一个带有 Button 和 ListView 的 UserControl。
模型
public class Item
{
private string _name = string.Empty;
public string Name
{
get
{
return _name;
}
set
{
_name = value;
}
}
}
视图模型
public class ViewModel : NotifyProperty
{
private Command addCommand;
public ICommand AddCommand
{
get
{
if (addCommand == null)
addCommand = new Command(addItem);
return addCommand;
}
}
private ObservableCollection<Item> _itemCollection;
public ViewModel()
{
ItemCollection = new ObservableCollection<Item>();
Item newItem = new Item();
newItem.Name = "Joe";
ItemCollection.Add(newItem);
}
public ObservableCollection<Item> ItemCollection
{
get
{
return _itemCollection;
}
set
{
_itemCollection = value;
OnPropertyChanged("ItemCollection");
}
}
private void addItem(Object obj)
{
Item newItem = new Item();
newItem.Name = "Chris";
ItemCollection.Add(newItem);
}
}
用户控件 (XAML)
<UserControl.DataContext>
<local:ViewModel />
</UserControl.DataContext>
<UserControl.Resources>
<DataTemplate x:Key="ItemTemplate">
<StackPanel Orientation="Vertical">
<Label Content="{Binding Name}" />
</StackPanel>
</DataTemplate>
</UserControl.Resources>
<Grid>
<DockPanel>
<Button Width="100" Height="30" Content="Add" Command="{Binding AddCommand}" DockPanel.Dock="Top" />
<ListView ItemTemplate="{StaticResource ItemTemplate}" ItemsSource="{Binding ItemCollection}" />
</DockPanel>
</Grid>
然后我像这样将它添加到我的 MainWindow
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.mainContentControl.Content = new ListControl();
}
}
这工作正常,当我单击“添加”按钮时,名称“Chris”被添加到 ListView。
现在我向 MainView 添加一个按钮并将其 Command 属性绑定到我的 ViewModel,如下所示:
<Grid>
<DockPanel>
<Button Width="100" Height="30" Content="Add" Command="{Binding AddCommand}" DockPanel.Dock="Top">
<Button.DataContext>
<local:ViewModel />
</Button.DataContext>
</Button>
<ContentControl x:Name="mainContentControl" />
</DockPanel>
</Grid>
当我在 MainWindow 中单击此按钮时,命令被发送到 ViewModel,addItem 事件被调用,名称“Chris”被添加到 ItemCollection,但 ListView 不会更新。我究竟做错了什么?