DateTimePicker OnValueChanged事件被引发两次

时间:2015-09-18 12:47:41

标签: c# wpf wpftoolkit

我正在使用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中可能存在的错误。

3 个答案:

答案 0 :(得分:1)

这似乎是因为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

然后从基类开始:

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

现在基类,似乎也经历了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&lt;&gt;是我在How can I find WPF controls by name or type?帖子

上找到的功能

使用最终摘要进行更新

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

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

在DateTimeUpDown.RaiseValueChangedEvent()中有代码来检查TemplatedParent是否是一个TimePicker以防止重新提升,但是事件是从DateTimePicker或TimePicker引发的,TemplatedParent似乎总是似乎是DateTimePicker,因此你失败了得到这个事件两次。

我在WPFToolkit项目网站上提出了一个关于调查结果的错误: https://wpftoolkit.codeplex.com/workitem/22014

答案 1 :(得分:1)

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

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

由于我没有在此控件中显示时间戳,我还要确保它是具有焦点的datetimepicker,而不是时间戳。可能是多余的

答案 2 :(得分:0)

我通过比较原始来源和来源来解决了这个问题。

e.OriginalSource == e.Source