本文介绍了WPF通知中的可观察集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Hi Experts
我将组合框"与可观察的集合"绑定,但是添加项目后,它不是自动刷新".
我有C#代码.是
Hi Experts
I Bind Combobox with Observable Collection but After add Item It is not Refresh Auto.
I Have C# Code. is
class ClsEmp : INotifyPropertyChanged
{
int _EmpCode;
public int EmpCode
{
get {return _EmpCode ;}
set { _EmpCode = value; NotifyPropertyChanged("EmpCode"); }
}
string _EmpName;
public string EmpName
{
get { return _EmpName; }
set { _EmpName = value; NotifyPropertyChanged("EmpName"); }
}
System.Collections.ObjectModel.ObservableCollection<ClsEmp> dataItem = new System.Collections.ObjectModel.ObservableCollection<ClsEmp>();
public ObservableCollection<ClsEmp> DropDownValues
{
get
{
return dataItem;
}
set
{
dataItem = value;
NotifyPropertyChanged("DropDownValues");
}
}
public ClsEmp(int EmpCode,string EmpName)
{
EmpCode = this.EmpCode;
EmpName = this.EmpName;
}
public ClsEmp()
{
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string strPropertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(strPropertyName));
}
}
}
和与Combobox绑定的代码;
and Code For Bind With Combobox;
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
LoadCombo();
}
ClsEmp cls = new ClsEmp();
private void btnAdd_Click(object sender, RoutedEventArgs e)
{
cls.EmpCode = 6;
cls.EmpName = txt.Text;
cls.DropDownValues.Add(cls);
}
private void LoadCombo()
{
cls.DropDownValues.Add(new ClsEmp { EmpCode = 1, EmpName = "A" });
cls.DropDownValues.Add(new ClsEmp { EmpCode = 2, EmpName = "B" });
cls.DropDownValues.Add(new ClsEmp { EmpCode = 3, EmpName = "C" });
cls.DropDownValues.Add(new ClsEmp { EmpCode = 4, EmpName = "D" });
cls.DropDownValues.Add(new ClsEmp { EmpCode = 5, EmpName = "E" });
cmb.ItemsSource = cls.DropDownValues.ToList();
}
}
.Xmal代码为
.Xmal Code is
<ComboBox x:Name="cmb" Grid.Row="1" Grid.Column="1"
DisplayMemberPath="EmpName" ItemsSource="{Binding Source={x:Static Application.Current}, Path=DropDownValues , Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"></ComboBox>
<TextBox x:Name="txt" Grid.Row="1" Grid.Column="2" Text="{Binding EmpName}"></TextBox>
<Button x:Name="btnAdd" Grid.Row="1" Grid.Column="3" Content="Add" Click="btnAdd_Click"></Button>
谢谢你
Dinesh Sharma
Thank u
Dinesh Sharma
推荐答案
cmb.ItemsSource = cls.DropDownValues.ToList();
没有意义,您正在获取副本,而不是您的DropDownValues
列表引用.不要使用这样的ToList
方法,将其更改为:
makes no sense, you''re grabbing a copy, not a reference of your DropDownValues
list. Don'' use the ToList
method like that, change it to:
cmb.ItemsSource = cls.DropDownValues;
它应该可以工作(我实际上没有尝试过).
希望这会有所帮助,
Fredrik Bornander
and it should work (I haven''t actually tried it).
Hope this helps,
Fredrik Bornander
这篇关于WPF通知中的可观察集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!