[英]WPF Databinding Not Updating UI
I have a XAML and CS file for a UserControl. 我有一个用于UserControl的XAML和CS文件。 I have my data stored in a Singleton class which implements INotifyPropertyChanged, and it binds to a ListBox in the UserControl.
我将数据存储在实现INotifyPropertyChanged的Singleton类中,并将其绑定到UserControl中的ListBox。
This is the XAML databinding: 这是XAML数据绑定:
<ListBox Name="ModsListBox"
ItemsSource="{Binding ModControls}"
Visibility="Visible"
Width="350"
Height="Auto">
</ListBox>
The datacontext is being set in the CS file as followings: 数据上下文在CS文件中的设置如下:
DataContext = ModDirector.Instance;
InitializeComponent();
In the code there is a method for adding elements which adds the datastructure which is being bound and then calls OnPropertyChanged(), however the UI never updates. 在代码中,有一种添加元素的方法,该方法添加要绑定的数据结构,然后调用OnPropertyChanged(),但是UI永远不会更新。
/// <summary>
/// Adds a mod and sends event to update UI elements bound to ModContols
/// </summary>
/// <param name="modUserControl"></param>
/// <param name="index"></param>
public void AddMod(ModUserControl modUserControl, int? index = null)
{
if (index != null)
{
_modControls.Insert(index.Value, modUserControl);
}
else
{
_modControls.Add(modUserControl);
}
OnPropertyChanged("ModControls");
}
Just for completion here is the property it is being bound to: 只是为了完成,这里是它绑定到的属性:
/* Properties */
public List<ModUserControl> ModControls
{
get { return _modControls; }
set
{
_modControls = value;
OnPropertyChanged();
}
}
/* End Properties */
And the code for OnPropertyChanged 以及OnPropertyChanged的代码
/// <summary>
/// Fires PropertyChanged event notifying the UI elements bound
/// </summary>
/// <param name="propertyName"></param>
[NotifyPropertyChangedInvocator]
private void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
var handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
Is there some reason the event would not be propagated? 是否有某些原因导致事件无法传播?
将您的List<ModUserControl>
更改为ObservableCollection<ModUserControl>
。
Your public List<ModUserControl> ModControls
should probably be an ObservableCollection<>
instead, so you can remove your manual calls to OnPropertyChanged("ModControls");
您的
public List<ModUserControl> ModControls
可能应该是ObservableCollection<>
,因此您可以删除对OnPropertyChanged("ModControls");
手动调用OnPropertyChanged("ModControls");
. 。 Your
ModControls
did not actually change. 您的
ModControls
实际上并没有改变。 It's still the very same instance. 仍然是同一实例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.