WPF-集合通知更改《八》

集合通知更改,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博客

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

故里2130

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值