Wpf ObservableCollection添加/删除操作不支持';t更新xaml端的ItemsControl
假设我有一个数据类:Wpf ObservableCollection添加/删除操作不支持';t更新xaml端的ItemsControl,wpf,observablecollection,itemscontrol,Wpf,Observablecollection,Itemscontrol,假设我有一个数据类: class MyData { public string FirstName {get;set;} public string LastName {get;set;} } 然后在我的视图模型中 class MyViewModel : ModelBase // assume this has all the work behind for prop notification changes { private ObservableCollection
class MyData
{
public string FirstName {get;set;}
public string LastName {get;set;}
}
然后在我的视图模型中
class MyViewModel : ModelBase // assume this has all the work behind for prop notification changes
{
private ObservableCollection<MyData> addedData = new ObservableCollection<MyData>();
public ObservableCollection<MyData> AddedData
{
get
{
return this.addedData;
}
set
{
this.addedData = value;
this.RaisePropertyChangedEvent();
}
}
public void AddDataRequestHandler()
{
this.AddedData.Add(new MyData() {some firstname and lastname}); //prototyping
}
}
classmyviewmodel:ModelBase//假设这已经完成了所有关于道具通知更改的工作
{
私有ObservableCollection AddData=新ObservableCollection();
公共可观测收集数据
{
收到
{
返回此.addedata;
}
设置
{
此。addedData=值;
this.RaisePropertyChangedEvent();
}
}
public void AddDataRequestHandler()
{
this.addedata.Add(new MyData(){some firstname and lastname});//原型
}
}
在xaml方面,我有类似的东西
<Grid
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Button Grid.Row="0" Content="Add" Command="{Binding Path=AddDataCommand}" />
<ItemsControl Grid.Row="1" ItemsSource="{Binding Path=AddedData}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<ItemsControl ItemsSource="{Binding}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Path=FirstName}" />
<TextBlock Text=" - " />
<TextBlock Text="{Binding Path=LastName}" />
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>
我的缺点是,我没有注意到我在xaml方面有过多的嵌套。因此ItemsControl应该简单得多,如下所示,并且在以下情况下可以正常工作:
<Grid
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Button Grid.Row="0" Content="Add" Command="{Binding Path=AddDataCommand}" />
<ItemsControl Grid.Row="1" ItemsSource="{Binding Path=AddedData}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Path=FirstName}" />
<TextBlock Text=" - " />
<TextBlock Text="{Binding Path=LastName}" />
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>
尝试从ctor初始化集合,并为集合属性引发已更改的属性。如果这是有意义的,因为您从未通知AddedData属性已更改。