为什么在Silverlight中为DatePicker
设置空值时,不会触发PropertyChangedEvent?
这是我的示例XAML
<UserControl x:Class="ValidationExamples.MainPage"
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:ig="http://schemas.infragistics.com/xaml"
xmlns:controls='clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls'
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="400">
<Grid x:Name="LayoutRoot" Background="White">
<StackPanel>
<controls:DatePicker Height="20" Width="100" x:Name="DatePicker" SelectedDate="{Binding Path=DOB, Mode=TwoWay}"/>
<Button Height="20" Width="100" Click="Button_Click" Content="Break"/>
</StackPanel>
</Grid>
</UserControl>
代码背后:
public partial class MainPage : UserControl
{
private Model MyModel;
public MainPage()
{
InitializeComponent();
this.MyModel = new Model();
this.MyModel.DOB = DateTime.Now;
this.DataContext = this.MyModel;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
// Empty on purpose
}
}
我的模型代码(如您所见,我尝试Nullable<DateTime>
和DateTime
):
public class Model : INotifyPropertyChanged
{
private Nullable<DateTime> dob;
public Nullable<DateTime> DOB
{
get
{
return this.dob;
}
set
{
this.dob = value;
NotifyPropertyChanged("DOB");
}
}
//private DateTime dob;
//public DateTime DOB
//{
// get
// {
// return this.dob;
// }
// set
// {
// this.dob = value;
// NotifyPropertyChanged("DOB");
// }
//}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string property)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(property));
}
}
}
答案 0 :(得分:0)
你不应该绑定SelectedDate
而不是DatePicker
的{{1}}属性吗?
答案 1 :(得分:0)
我遇到的问题是ConvertBack
抛出异常,这就是为什么PropertyChanged
从未被解雇的原因。
我还将Date控件更改为绑定到SelectedDate
而不是Text
Mark Heath 建议。
更新了Xaml
<controls:DatePicker Height="20" Width="100" x:Name="DatePicker" SelectedDate="{Binding Path=DOB, Mode=TwoWay, Converter={StaticResource DateConverter}}"/>
这是我的转换器......
public class DateConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
DateTime? result = null;
DateTime result2;
if (value != null)
{
if (!String.IsNullOrEmpty(value.ToString()))
{
if (DateTime.TryParse(value.ToString(), out result2))
{
return result2;
}
}
}
return result;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
DateTime? result = null;
DateTime result2;
if (value != null)
{
if (!String.IsNullOrEmpty(value.ToString()))
{
if (DateTime.TryParse(value.ToString(), out result2))
{
return result2;
}
}
}
return result;
}
}