![](/img/trans.png)
[英]How to refresh combobox after changing selection in another combobox in WPF
[英]WPF ComboBox Refresh After Collection Update
我在wpf
使用ComboBox
,如下所示,并且想更新ComboBox
,如果我更新collection:-
<xmlns:dataProvider="clr-namespace:DataProvider"
<UserControl.Resources>
<dataProvider:BackOfficeDataProvider x:Key="DataProvider"/>
</UserControl.Resources>
<ComboBox x:Name="groupGroupNameCombo" HorizontalAlignment="Left" Margin="368,123,0,0" VerticalAlignment="Top" Width="226" Height="31" SelectionChanged="groupGroupNameCombo_SelectionChanged" DisplayMemberPath="GroupName" SelectedItem="{Binding ParentID, Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" ItemsSource="{Binding GroupParentList, Mode=TwoWay, NotifyOnTargetUpdated=True, NotifyOnSourceUpdated=True, Source={StaticResource DataProvider}}" IsSynchronizedWithCurrentItem="True">
</ComboBox>
Class BackOfficeDataProvider {
public static ObservableCollection<Categories> groupParentList = null;
public virtual ObservableCollection<Categories> GroupParentList
{
get { return groupParentList ; }
set
{
groupParentList = value;
// Call OnPropertyChanged whenever the property is updated
OnPropertyChanged("GroupParentList");
}
}
public void loadComboListData();
{
GroupParentList = (ObservableCollection<Categories>) //fetching data from database using NHibernate directly getting list ;
}
}
我的前端类有刷新按钮:-
private void RefreshButton_Click(object sender, RoutedEventArgs e)
{
new BackOfficeDataProvider().loadComboListData();
}
当应用程序加载该时间时,我可以在combobox
看到该项目,但是当我单击“刷新”按钮时,它从数据库加载更新的数据,但不更新combobox
直到我使用以下代码
groupGroupNameCombo.ItemsSource = null;
groupGroupNameCombo.ItemSource = GroupParentList ;
我必须总是刷新刷新combobox
,这是我必须做的手动操作,如果我更新集合,该如何使其自动运行,那么它应该同时更新combobox
,而我不需要使用上述解决方法。
我认为这样做可能与打破组合框和ObservableCollection之间的耦合有关:
GroupParentList = //fetching data from database;
尝试以下方法:
var dbCategories = // Get data from DB
GroupParentList.Clear();
foreach (var item in dbData)
GroupParentList.Add(item);
重点是更新集合中的项目,而不是集合本身。
另外,尝试像这样定义您的集合,它不必被多次实例化(即没有设置器):
public static ObservableCollection<Categories> groupParentList = null;
public virtual ObservableCollection<Categories> GroupParentList
{
get
{
if (groupParentList == null)
groupParentList = new ObservableCollection<Categories>();
return groupParentList;
}
}
Hogler是正确的,将新的ObservableCollection对象分配给binding属性的方法将破坏绑定的工作方式。 为了使ObservableCollection工作,您将需要修改集合本身中的项目,ObservableCollection负责将列表更改发布到绑定目标。 将新集合分配给绑定目标时,除非再次发布PropertyChanged事件以注册此新绑定源,否则列表将不会刷新。
在以后的评论中,您确实声明仅实例化ObservableCollection一次,这在您发布的代码中并不明显。 在我看来,它不起作用的原因是因为每次运行“ loadComboListData”时,都会向“ GroupParentList”分配一个新集合。
试试这个..一旦完成从groupParentList
的数据库中获取数据,在Line下面添加,它将按以下方式工作:
GroupParentList = new ObservableCollection<Categories>(groupParentList )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.