我的 viewmodel 类中有一个 DateTime 属性(比如 DateVal),而 View 中有一个 DatePicker 控件。
<DatePicker Grid.Column="1"
Width="100"
Height="30"
SelectedDate="{Binding DateVal,ValidatesOnDataErrors=True}"/>
问题是,如果用户删除 Datepicker 控件的文本框中显示的日期,DateVal 属性不会更改其值。如何跟踪用户已删除日期选择器文本框中显示的日期?
问候,
阿尼尔类
日期选择器控件如下所示
现在,如果用户只是删除日期选择器文本框中显示的日期,则控件如下所示
此时 DateVal 的值与以前相同。
仅当用户单击日历图标时 Date 才被分配一个 null 值。
当用户使文本框为空时,如何同时跟踪更改?
View 模型代码
public DateTime? DateVal
{
get
{
return this.dateVal;
}
set
{
this.dateVal = value;
this.OnPropertyChanged("DateVal");
}
}
xml代码
<DatePicker Name="datePickerDateVal"
Grid.Column="1"
Width="100"
Height="30"
SelectedDate="{Binding DateVal,ValidatesOnDataErrors=True}"
Text="{Binding DateVal,ValidatesOnDataErrors=True,UpdateSourceTrigger=PropertyChanged}" />
我希望当用户清除 Date Picker 文本框时必须调用 DateVal 的 setter 属性
最佳答案
不幸的是,DatePicker 的文本框设置为仅在失去焦点时才更新其绑定(bind)源。好消息是您可以通过 DatePicker
连接到该过程。的ControlTemplate
:
XAML:
<DatePicker SelectedDate="{Binding DateVal}" x:Name="__picker" />
以及背后的代码:
DateTime? _dateVal = DateTime.Today;
public Nullable<DateTime> DateVal
{
get { return _dateVal; }
set
{
if (_dateVal == value)
return;
_dateVal = value;
OnPropertyChanged("DateVal");
}
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
DatePickerTextBox pickerTextBox = __picker.Template.FindName("PART_TextBox", __picker) as DatePickerTextBox;
if (pickerTextBox == null)
return;
pickerTextBox.TextChanged += new TextChangedEventHandler(pickerTextBox_TextChanged);
}
void pickerTextBox_TextChanged(object sender, TextChangedEventArgs e)
{
DatePickerTextBox tb = sender as DatePickerTextBox;
if (tb == null)
return;
if (string.IsNullOrEmpty(tb.Text))
{
__picker.SelectedDate = null;
}
}
我只是摆弄它,我的猜测是你没有得到更频繁更新的原因是文本和选定日期属性之间的循环关系。不过,确保我们获得 null DateTimes 的更新应该没问题。
编辑
更新了事件处理程序以更新选择器
SelectedDate
属性而不是 View 模型中的属性。这样,您可以将 hack 完全保留在 View 中,同时保持与 View 模型无关。
关于wpf - 在 View 模型中验证 DateTime 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14750324/