【问题标题】:textbox is being filled but datepicker is not via mvvm binding正在填充文本框,但日期选择器不是通过 mvvm 绑定
【发布时间】:2014-03-24 15:49:57
【问题描述】:

我有一个包含日期的文本框,我想将其转换为日期选择器以进行双向绑定。但不幸的是,日期选择器没有显示日期。

                    <TextBox Grid.Row="1"
                         Grid.Column="4"
                         IsReadOnly="False"
                         Text="{Binding Path=BirthDate,
                                        Mode=OneWay,
                                        StringFormat='dd/MM/yyyy'}" />

以下代码不起作用,selecteddate显示为空...(虽然里面有值)

                <DatePicker Grid.Row="1"
                           Grid.Column="4" FirstDayOfWeek="Monday" SelectedDate="{Binding BirthDate, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" ></DatePicker>

在应用程序的另一个位置,我也有一个可以工作的日期选择器:

            <DatePicker x:Name="DatePicker" 
                    Grid.Row="3"
                    Grid.Column="1"
                    FirstDayOfWeek="Monday"
                    SelectedDate="{Binding Parameter.PAR_Date,
                                           Mode=TwoWay}"  />

我看不出我做错了什么,看起来很简单。

我可以在日期选择器中输入一个日期,这很有效...太奇怪了...欢迎任何想法...

编辑:

通过使用 snoop 并查看 datepicker 上的绑定更进一步,它似乎有一个错误,我似乎有不同的预期类型:

System.Windows.Data Error: 1 : Cannot create default converter to perform 'two-way' conversions between types 'EVD.Framework.NullableDateTime' and 'System.Nullable`1[System.DateTime]'. Consider using Converter property of Binding. BindingExpression:Path=Birthdate; DataItem='SomeModel' (HashCode=31671132); target element is 'DatePicker' (Name=''); target property is 'SelectedDate' (type 'Nullable`1')
System.Windows.Data Error: 5 : Value produced by BindingExpression is not valid for target property.; Value='04/10/1929' BindingExpression:Path=Birthdate; DataItem='SomeModel' (HashCode=31671132); target element is 'DatePicker' (Name=''); target property is 'SelectedDate' (type 'Nullable`1')

编辑 2:

就是这样,在代码中日期时间是 NullableDateTime。感谢每个提出想法的人,尤其是 Viv。为每个有不错建议的人投票:-)

【问题讨论】:

  • 你能显示更多代码吗?例如,您在哪里以及如何设置 BirthDate 的值?
  • 对我来说很好用。你确定你DatePicker.DataContext 是正确的并且它实际上能够找到该属性吗?您可以在运行时使用Snoop 进行检查,以确保DataContext 正确且SelectedDate 绑定在DatePicker 上有效。
  • 您是否在即时窗口中检查过绑定错误?
  • 嘿 Viv,通过使用 Snoop,我离问题更近了一步。谢谢你的提示。查看我的编辑。

标签: wpf mvvm datepicker propertychanged


【解决方案1】:

这篇文章很好地解释了 StringFormat: http://elegantcode.com/2009/04/07/wpf-stringformat-in-xaml-with-the-stringformat-attribute/

您需要记住在格式化时使用{0}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-16
    • 1970-01-01
    • 2017-07-26
    • 2020-12-26
    • 1970-01-01
    相关资源
    最近更新 更多