DateTimePicker OnValueChanged 事件被引发两次

DateTimePicker OnValueChanged event is raised twice

我正在使用 Extended WPF Toolkit Community Edition 库版本 2.5 中的 DateTimePicker WPF 控件。

我的问题是,当我选择一个日期时,OnValueChanged 事件被引发了两次而不是一次。

这是我使用的代码:

XAML:

<StackPanel>
    <xctk:DateTimePicker AutoCloseCalendar="True"  Name="picker"  Width="400" Height="40" ValueChanged="UpDownBase_OnValueChanged"/>
    <ListBox Height="300" Name="listbox"></ListBox>
</StackPanel>

后面的 C# 代码:

private void UpDownBase_OnValueChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
{
    var value = picker.Value;

    if (value == null)
        listbox.Items.Add("[NULL]");
    else
        listbox.Items.Add(value.Value.ToString(CultureInfo.InvariantCulture));
}

现在,每当我选择一个新日期时,列表框中都会填充两个新项目。我也调试了程序,确认事件处理器确实被调用了两次。

我该如何解决这个问题?

更新:

我试过2.4版,好像问题没有了。现在看来,这可能是 2.5 版中的一个可能错误。

这似乎是因为 2.5 中的事件是从以下位置触发的:

at Xceed.Wpf.Toolkit.DateTimePicker.OnValueChanged(Nullable`1 oldValue, Nullable`1 newValue) in C:\Users\Mark Vinten\Downloads\wpftoolkit-114314\Main\Source\ExtendedWPFToolkitSolution\Src\Xceed.Wpf.Toolkit\DateTimePicker\Implementation\DateTimePicker.cs:line 264

然后从基地 class:

at Xceed.Wpf.Toolkit.TimePicker.OnValueChanged(Nullable`1 oldValue, Nullable`1 newValue) in C:\Users\Mark Vinten\Downloads\wpftoolkit-114314\Main\Source\ExtendedWPFToolkitSolution\Src\Xceed.Wpf.Toolkit\TimePicker\Implementation\TimePicker.cs:line 264

现在基础class,似乎也经历了 CLR 绑定过程,提示这是绑定值。我仍在研究为什么会这样,但解决方法是这样使用 Binding:

MainWindow.cs

    public DateTime? DateTimeValue
    {
        get { return (DateTime?)GetValue(DateTimeValueProperty); }
        set { SetValue(DateTimeValueProperty, value); }
    }

    // Using a DependencyProperty as the backing store for DateTimeValue.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty DateTimeValueProperty =
        DependencyProperty.Register("DateTimeValue", typeof(DateTime?), typeof(MainWindow), new PropertyMetadata(null, new PropertyChangedCallback(DateTimeValueProperty_Changed)));

    private static void DateTimeValueProperty_Changed(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        MainWindow mw = d as MainWindow;
        System.Diagnostics.Debug.WriteLine("d is " + d == null ? "null" : d.GetType().FullName);
        if (mw != null && e.Property == DateTimeValueProperty)
        {
            var value = e.NewValue as DateTime?;
            var listbox = FindChild<ListBox>(mw, "listbox");

            if (value == null)
                listbox.Items.Add("[NULL]");
            else
                listbox.Items.Add(value.Value.ToString(System.Globalization.CultureInfo.InvariantCulture));
        }
    }

    /// <summary>
    /// Finds a Child of a given item in the visual tree. 
    /// </summary>
    /// <param name="parent">A direct parent of the queried item.</param>
    /// <typeparam name="T">The type of the queried item.</typeparam>
    /// <param name="childName">x:Name or Name of child. </param>
    /// <returns>The first parent item that matches the submitted type parameter. 
    /// If not matching item can be found, 
    /// a null parent is being returned.</returns>
    public static T FindChild<T>(DependencyObject parent, string childName)
       where T : DependencyObject
    {
        // Confirm parent and childName are valid. 
        if (parent == null) return null;

        T foundChild = null;

        int childrenCount = VisualTreeHelper.GetChildrenCount(parent);
        for (int i = 0; i < childrenCount; i++)
        {
            var child = VisualTreeHelper.GetChild(parent, i);
            // If the child is not of the request child type child
            T childType = child as T;
            if (childType == null)
            {
                // recursively drill down the tree
                foundChild = FindChild<T>(child, childName);

                // If the child is found, break so we do not overwrite the found child. 
                if (foundChild != null) break;
            }
            else if (!string.IsNullOrEmpty(childName))
            {
                var frameworkElement = child as FrameworkElement;
                // If the child's name is set for search
                if (frameworkElement != null && frameworkElement.Name == childName)
                {
                    // if the child's name is of the request name
                    foundChild = (T)child;
                    break;
                }
            }
            else
            {
                // child element found.
                foundChild = (T)child;
                break;
            }
        }

        return foundChild;
    }

MainWindow.xaml

    <StackPanel DataContext="{Binding RelativeSource={RelativeSource AncestorType={x:Type local:MainWindow}}}">
        <xctk:DateTimePicker AutoCloseCalendar="True"  Name="picker"  Width="400" Height="40" Value="{Binding DateTimeValue}" />
        <ListBox Height="300" Name="listbox"></ListBox>
    </StackPanel>

这使用绑定系统自动检查值是否已更改并且仅在更改时引发事件。

注意:FindChild<> 是我在这个 How can I find WPF controls by name or type? post

上找到的函数

更新最终摘要

这似乎是因为在 DateTimePicker 中嵌入了一个 TimePicker 来提供该功能。不幸的是,DateTimePicker 和 TimePicker 都派生自相同的基础,因此在 UpDownBase 中引发相同的路由事件,其中 T 是 DateTime?。

如果您检查事件参数,e.RoutedEVent 始终是 UpDownBase.OnValueChanged,因为这是引发事件的 class。 e.Source 或 e.OriginalSource 始终是 DateTimePicker 本身,这意味着您没有有用的方法来过滤掉一个或另一个事件。

DateTimeUpDown.RaiseValueChangedEvent() 中有代码检查 TemplatedParent 是否是 TimePicker 以防止重新引发但是事件是从 DateTimePicker 还是 TimePicker 引发的 TemplatedParent 似乎总是 DateTimePicker 所以失败因此你得到了两次事件。

我在 WPFToolkit 项目网站上提出了一个错误: https://wpftoolkit.codeplex.com/workitem/22014

我通过检查事件的原始来源解决了这个问题problem/bug。

 if(e.OriginalSource is Xceed.Wpf.Toolkit.DateTimePicker)
    {
       if(((Xceed.Wpf.Toolkit.DateTimePicker)e.OriginalSource).IsFocused == true)
       {
          ResetDataTable();
       }
    }

由于我没有在此控件中显示时间选择器,因此我还要确保焦点是日期时间选择器,而不是时间选择器。可能是多余的

我通过比较原出处和出处解决了这个问题

e.OriginalSource == e.Source