Гро*_*ный 7 data-binding wpf xaml observablecollection mvvm
问题很简单:何时ItemsSource更新Combobox不会"刷新",例如新项目似乎没有添加到组合框中的项目列表中.
我已经尝试了解决这个问题的解决方案:WPF - 自动刷新组合框内容,没有运气.
这是我的代码,XAML:
<ComboBox Name="LeadTypeComboBox" ItemsSource="{Binding LeadTypeCollection}" />
Run Code Online (Sandbox Code Playgroud)
视图模型:
public ObservableCollection<XmlNode> LeadTypeCollection { get; set; }
Run Code Online (Sandbox Code Playgroud)
我更新此集合的方式是在单独的方法中,该方法从更新的XML文件加载数据: this.LeadTypeCollection = GetLeadTypesDataSource();
我也尝试过Add用于测试目的:
this.LeadTypeCollection = GetLeadTypesDataSource();
ItemToAdd = LeadTypeCollection[LeadTypeCollection.Count - 1];
this.LeadTypeCollection.Add(ItemToAdd);
Run Code Online (Sandbox Code Playgroud)
代码更新集合肯定开始了,我可以在调试时看到这个集合中的新项目,但我没有在组合框中看到它们.
在xaml代码隐藏工作中这样做:LeadTypeComboBox.ItemsSource = MyViewModel.GetLeadTypesDataSource();但我想用MVVM实现这一点,即代码必须在ViewModel中,它不知道LeadTypeComboBox控件.
Firedragons的答案可行,但我更喜欢初始化LeadTypeCollection一次并使用clear,添加remove来更新你的集合.
var update = GetLeadTypesDataSource();
this.LeadTypeCollection.Clear();
foreach(var item in update)
{
this.LeadTypeCollection.Add(item);
}
Run Code Online (Sandbox Code Playgroud)
如果datacontext是正确的,你的xaml绑定应该有效
<ComboBox Name="LeadTypeComboBox" ItemsSource="{Binding LeadTypeCollection}" />
Run Code Online (Sandbox Code Playgroud)
我想我以前见过,解决方法是更新collection属性以引发更改。
即
public class MyViewModel : INotifyPropertyChanged
{
private ObservableCollection<XmlNode> leadTypeCollection;
public string LeadTypeCollection
{
get { return leadTypeCollection; }
set
{
if (value != leadTypeCollection)
{
leadTypeCollection = value;
NotifyPropertyChanged("LeadTypeCollection");
}
}
public MyViewModel()
{
leadTypeCollection = new ObservableCollection<XmlNode>();
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String info)
{
PropertyChanged.Raise(this, info);
}
}
Run Code Online (Sandbox Code Playgroud)
我有一个扩展方法来提高属性(如在stackoverflow上的其他地方所发现的):
public static void Raise(this PropertyChangedEventHandler handler, object sender, string propertyName)
{
if (null != handler)
{
handler(sender, new PropertyChangedEventArgs(propertyName));
}
}
Run Code Online (Sandbox Code Playgroud)
一个简单的方法是使用空列表更改 ItemsSource,然后将其更改回更新后的源。我的项目中的一个片段正在运行:
RulesTable.ItemsSource = Rules.rulesEmpty;
RulesTable.ItemsSource = Rules.Get();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
23898 次 |
| 最近记录: |