c# - SourceUpdated 和 NotifyOnSourceUpdated 未在 ListBox 中触发

标签 c# .net wpf data-binding

我尝试在 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/

相关文章:

.net - WPF 可编辑数据网格,如 MS Access 和 MVVM

c# - 如何绑定(bind)到所属窗口的控制属性(来自对话框窗口)?

wpf - 我需要知道演示模型中的窗口句柄

c# - 基于标签和地理位置的 Instagram 提要

c# - Linq参数错误

c# - 使用 C# 构建 Excel 文件

c# - .NET 中是否有运行对象表

c# - 如何在C#中通过wifi路由器接收数据

c# - 多表单绑定(bind)数据

.net - 使用 jquery 填充下拉菜单并设置从 .NET SelectList 中选择的内容