【问题标题】:SourceUpdated with NotifyOnSourceUpdated not fired in ListBox在 ListBox 中未触发具有 NotifyOnSourceUpdated 的 SourceUpdated
【发布时间】:2018-05-04 21:27:31
【问题描述】:

我正在尝试在 ListBox 中使用 SourceUpdated 事件,但它不会触发。 我已将 ObservableCollection 绑定到 ListBox 的 ItemSource,设置 NotifyOnSourceUpdated = true,并且绑定工作正常 - 将新项目添加到集合后,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>

我错过了什么,它不起作用? 谢谢你的建议。

【问题讨论】:

    标签: c# .net wpf data-binding


    【解决方案1】:

    SourceUpdated 仅在可以接受输入并直接更改数据绑定源值的元素上触发。

    https://msdn.microsoft.com/en-us/library/system.windows.data.binding.sourceupdated(v=vs.110).aspx

    在这种情况下,列表框本身不会更新集合,而是通过单击按钮来更新集合。这与触发 SourceUpdated 事件的列表框无关。

    只有可以接受输入的输入元素,如文本框、复选框、单选按钮和使用这些控件的自定义控件,才能进行双向绑定并将其值传输回绑定到的源。

    您可能正在寻找 CollectionChanged,它会在集合中添加或删除项目时触发。

    https://msdn.microsoft.com/en-us/library/ms653375(v=vs.110).aspx

    Collection = new ObservableCollection<string>();
    Collection.CollectionChanged += (s, e) =>
    {
        // collection changed!
    };
    

    希望这会有所帮助!干杯!

    【讨论】:

    • 感谢您的回答。可惜有些事件是假的。
    • 谢谢@Rob.Ak,如果这个或任何答案已经解决了您的问题,请考虑通过单击复选标记接受它。这向更广泛的社区表明您已经找到了解决方案,并为回答者和您自己提供了一些声誉。没有义务这样做。
    猜你喜欢
    • 1970-01-01
    • 2017-06-09
    • 1970-01-01
    • 1970-01-01
    • 2011-07-26
    • 2023-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多