集合通知更改,ObservableCollection。属性通知更改,适合单个属性,如果是多个属性的集合数据,使用ObservableCollection。
1.先创建一个类
public class Students
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public bool B { get; set; }
}
2.创建Student集合
ObservableCollection<Students> infos = new ObservableCollection<Students>() {
new Students(){ Id=1, Age=11, Name="Tom",B=false},
new Students(){ Id=2, Age=12, Name="Darren",B=false},
new Students(){ Id=3, Age=13, Name="Jacky",B=false},
new Students(){ Id=4, Age=14, Name="Andy",B=false}
};
3.给界面的控件赋值
4.界面代码
<Grid>
<StackPanel Height="295" HorizontalAlignment="Left" Margin="10,10,0,0" Name="stackPanel1" VerticalAlignment="Top" Width="427">
<TextBlock Height="23" Name="textBlock1" Text="学员编号:" />
<TextBox Height="23" Name="txtStudentId" Width="301" HorizontalAlignment="Left"/>
<TextBlock Height="23" Name="textBlock2" Text="学员列表:" />
<ListBox Height="156" Name="lbStudent" Width="305" HorizontalAlignment="Left">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Name="stackPanel2" Orientation="Horizontal">
<TextBlock Text="{Binding Id,Mode=TwoWay}" Margin="5" Background="Red"/>
<TextBlock Text="{Binding Name,Mode=TwoWay}" Margin="5"/>
<TextBlock Text="{Binding Age,Mode=TwoWay}" Margin="5"/>
<TextBlock Text="{Binding B,Mode=TwoWay}" Margin="5"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<Button Content="Button" Height="23" Name="button1" Width="75" HorizontalAlignment="Left" Click="button1_Click" />
</StackPanel>
</Grid>
5.button事件
private void button1_Click(object sender, RoutedEventArgs e)
{
infos[1] = new Students() { Id = 4, Age = 14, Name = "这是一个集合改变",B=true };
infos[2].Name = "这是一个属性改变";
infos[3] = new Students() { Id = 666, Age = 66, Name = "666", B = true };
}
此处的Name值需要Students类实现INotifyPropertyChanged通知,界面就会变化了。
6.效果
来源:WPF-集合通知更改《八》_wpf observablecollection 修改属性_故里2130的博客-CSDN博客