积极答复者
继承了ObservableCollection接口的集合类,添加元素后,并没有自动更新绑定的集合控件的显示内容

问题
-
一:该集合类
public class NameList : ObservableCollection<PersonName> { public NameList() : base() { Add(new PersonName("Willa", "Cather")); Add(new PersonName("Isak", "Dinesen")); Add(new PersonName("Victor", "Hugo")); Add(new PersonName("Jules", "Verne")); } } public class PersonName { private string firstName; private string lastName; public PersonName(string first, string last) { this.firstName = first; this.lastName = last; } public string FirstName { get { return firstName; } set { firstName = value; } } public string LastName { get { return lastName; } set { lastName = value; } } }
二:xaml标签
<UserControl.Resources> <c:NameList x:Key="NameListData" /> <DataTemplate x:Key="NameItemTemplate"> <StackPanel Orientation="Horizontal"> <TextBlock Text="{Binding FirstName}" /> <TextBlock Text="," /> <TextBlock Text="{Binding LastName}" /> </StackPanel> </DataTemplate> </UserControl.Resources> <StackPanel> <ListBox Width="200" Height="200" VerticalAlignment="Top" Name="lbName" ItemsSource="{Binding Source={StaticResource NameListData}}" ItemTemplate="{StaticResource NameItemTemplate}" /> <StackPanel Orientation="Horizontal" HorizontalAlignment="Center" Margin="0,10,0,0"> <Label Content="FirstName:" /> <TextBox Name="txtFirstName" Width="60" /> <Label Content="LastName:" Margin="10,0,0,0" /> <TextBox Name="txtLastName" Width="60" /> </StackPanel> <Button x:Name="Add" Content="Add" Click="Add_Click" Width="60" Height="30" Margin="0,10,0,0" /> </StackPanel>
三:后置代码
public NameList nameList = new NameList(); private void Add_Click(object sender, RoutedEventArgs e) { nameList.Add(new PersonName(txtFirstName.Text, txtLastName.Text)); //https://nishantrana.me/2012/04/12/refresh-observablecollection-in-wpf/ CollectionViewSource.GetDefaultView(this.nameList).Refresh(); string a = nameList[0].FirstName; }
问题:
1、当ObservableCollection<T>添加一行时,会自动通知绑定该ObservableCollection<T>的控件并做相应修改。但没有看到此效果,为此
2、CollectionViewSource.GetDefaultView(this.nameList).Refresh();还是不行。
想请教,到底怎样才能在绑定的集合类添加元素后,自动反映到被绑定的结合控件显示的内容?
ly_he
- 已移动 Jack J JunMicrosoft contingent staff 2019年12月27日 6:09 wpf related
答案
全部回复
-
Hi,
我看你的代码,你又新建了一个NameList的对象,然后往里面添加一个PersonName,这样做不对。你应该像原来与Listbox绑定的NameList里面添加才可以,看我的代码:
NameList list=new NameList (); public MainWindow() { InitializeComponent(); Listbox1.ItemsSource = list; } private void Button_Click(object sender, RoutedEventArgs e) { list.Add(new PersonName("li","alex") ); }
Best Regards,
Alex
如果您对Visual Studio 或Microsoft Azure相关产品感兴趣,请点击此链接,或扫描以下二维码注册获取相关信息。
- 已编辑 Alex-KSGZ 2019年12月27日 6:24