我尝试在 ListBox 中使用 SourceUpdated 事件,但它没有触发。
我已将 ObservableCollection 绑定(bind)到 ListBox 的 ItemSource,设置 NotifyOnSourceUpdated = true
,并且绑定(bind)工作正常 - 将新项目添加到集合后,ListBox 显示新项目,但不触发事件。
MainWindow.xaml.cs:
public partial class MainWindow:Window
{
public ObservableCollection<string> Collection { get; set; }
public MainWindow()
{
InitializeComponent();
Collection = new ObservableCollection<string>();
var custBinding = new Binding()
{
Source = Collection,
NotifyOnSourceUpdated = true
};
intList.SourceUpdated += intList_SourceUpdated;
intList.SetBinding(ItemsControl.ItemsSourceProperty, custBinding);
}
private void intList_SourceUpdated(object sender, DataTransferEventArgs e)
{
MessageBox.Show("Updated!");
}
private void btnAddInt_Click(object sender, RoutedEventArgs e)
{
var randInt = new Random().Next();
Collection.Add(randInt.ToString());
}
}
MainWindow.xaml:
<Window x:Class="Test.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:Test"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<Button x:Name="btnAddInt" Content="Button" HorizontalAlignment="Left" Margin="41,31,0,0" VerticalAlignment="Top" Width="75" Click="btnAddInt_Click"/>
<ListBox x:Name="intList" HorizontalAlignment="Left" Height="313" Margin="160,31,0,0" VerticalAlignment="Top" Width="600"/>
</Grid>
我错过了什么,它不起作用? 谢谢您的建议。
最佳答案
SourceUpdated 仅在可以接受输入并直接更改数据绑定(bind)源值的元素上触发。
https://msdn.microsoft.com/en-us/library/system.windows.data.binding.sourceupdated(v=vs.110).aspx
在这种情况下,列表框本身不会更新集合,而是通过单击按钮来更新集合。这与列表框触发 SourceUpdated 事件无关。
只有可以接受输入(例如文本框、复选框、单选按钮和使用这些控件的自定义控件)的输入元素才能进行双向绑定(bind)并将其值传输回其绑定(bind)的源。
您可能正在寻找 CollectionChanged,它将在集合中添加或删除项目时触发。
https://msdn.microsoft.com/en-us/library/ms653375(v=vs.110).aspx
Collection = new ObservableCollection<string>();
Collection.CollectionChanged += (s, e) =>
{
// collection changed!
};
希望这有帮助!干杯!
关于c# - SourceUpdated 和 NotifyOnSourceUpdated 未在 ListBox 中触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50183259/