代码之家  ›  专栏  ›  技术社区  ›  Tewr

WPF日期选取器输入修改

  •  2
  • Tewr  · 技术社区  · 16 年前

    我正在使用wpf/c创建表单。我希望通过编程更改/解释用户在 wpf toolkit DatePicker .

    例如,用户键入“Today”,当控件失去焦点时,将使用“我的C”函数解释日期并将其设置为当前日期。

    我应该听lostfocus事件,还是有更好的方法来更改类型化输入日期的解析方式?

    我不想更改日期选取器的显示格式。我正在使用MVVM模式开发这个应用程序。

    2 回复  |  直到 16 年前
        1
  •  3
  •   Tewr    16 年前

    好吧,最后我研究了 DatePicker 在转换器等方面我做不了太多,因为大多数东西都是私有的,只有两种可用的格式是“短”和“长”。最后,我必须创建自己的控件,可能部分地使用Aviad上面的解决方案。然而,这里有一个快速的临时解决方案,直到那时(在哪里 DateHelper 是我的自定义分析器类):

       public class CustomDatePicker : DatePicker
        {
            protected override void OnPreviewKeyDown(KeyEventArgs e)
            {
                if (e.Key == Key.Enter)
                {
                    this.TryTransformDate();
                }
    
                base.OnPreviewKeyDown(e);
            }
    
            protected override void OnPreviewLostKeyboardFocus(KeyboardFocusChangedEventArgs e)
            {
                this.TryTransformDate();
                base.OnPreviewLostKeyboardFocus(e);
            }
    
            protected void TryTransformDate()
            {
                DateTime tryDate;
                if (DateHelper.TryParseDate(this.Text, out tryDate))
                {
                    switch (this.SelectedDateFormat)
                    {
                        case DatePickerFormat.Short: 
                            {
                                this.Text = tryDate.ToShortDateString();
                                break;
                            }
    
                        case DatePickerFormat.Long: 
                            {
                                this.Text = tryDate.ToLongDateString();
                                break;
                            }
                    }
                }
    
            }
        }
    
        2
  •  1
  •   Aviad P.    16 年前

    值转换器的典型场景。定义接受 string 并将其转换为 DateTime . 在绑定中,定义 UpdateSourceTrigger 成为 LostFocus 因此:

    <TextBox Text="{Binding DateText, 
                    Converter={StaticResource MyConverter}, 
                    UpdateSourceTrigger=LostFocus}"/>
    
    推荐文章