[英]How can I disable DatePicker from viewmodel WPF MVVM
I am developing a WPF application using WPF, I have a combobox which selected item is bound to viewmodel and i have a datepicker. 我正在使用WPF开发WPF应用程序,我有一个组合框,该组合框的选定项绑定到了viewmodel,并且我有一个日期选择器。 I want to Disable the datepicker in the view depending on the selecteditem of the combobox.
我想根据组合框的选定项在视图中禁用日期选择器。
the combo: 组合:
<ComboBox x:Name="comboBox2" Grid.Row="6" Grid.Column="1" SelectedIndex="0" ItemsSource="{Binding Path=DueDateOptions}" SelectedValue="{Binding Urgent}">
the datepicker: 日期选择器:
<DatePicker x:Name="datePicker1" Grid.Row="6" Grid.Column="2" SelectedDate="{Binding DueDate, Mode=TwoWay}"/>
how can I achieve this purpose, I hope for a little help. 我怎样才能达到这个目的,希望能有所帮助。
One way to achieve this is, adding a property to the ViewModel and binding IsEnabled property of the DatePicker to that. 实现此目的的一种方法是,向ViewModel添加一个属性,并将DatePicker的IsEnabled属性绑定到该属性。 Then you need to set the property inside the setter of Urgent property: (assuming that you have a property named Urgent in your ViewModel):
然后,您需要在Urgent属性的设置器中设置属性(假设您在ViewModel中有一个名为Urgent的属性):
class YourViewModel {
private bool allowPickDate;
public bool AllowPickDate {
get {
return this.allowPickDate;
}
set {
if (this.allowPickDate != value) {
this.allowPickDate = value;
this.OnPropertyChanged("AllowPickDate");
}
}
}
public UrgentType Urgent {
get {
....
}
set {
....
if (value == [whatever you expect]) {
this.AllowPickDate = true;
}
else {
this.AllowPickDate = false;
}
}
}
XAML: XAML:
<DatePicker x:Name="datePicker1" IsEnabled={Binding AllowPickDate} Grid.Row="6" Grid.Column="2" SelectedDate="{Binding DueDate, Mode=TwoWay}"/>
You can create property IsDatePickerEnabled in your viewmodel and bind property IsEnabled on datepicker to this property. 您可以在视图模型中创建属性IsDatePickerEnabled,并将日期选择器上的属性IsEnabled绑定到此属性。
<DatePicker x:Name="datePicker1" Grid.Row="6" Grid.Column="2" SelectedDate="{Binding DueDate, Mode=TwoWay}" IsEnabled="{Binding IsDatePickerEnabled}"/>
private bool _isDatePickerEnabled;
public bool IsDatePickerEnabled
{
get{return _isDatePickerEnabled;}
set
{
_isDatePickerEnabled = value;
OnPropertyChanged(()=>IsDatePickerEnabled);
}
}
Then in the setter of Urgent property call method which will determine whether the data picker is enabled or not. 然后在“紧急”属性调用方法的设置器中,该方法将确定是否启用了数据选择器。
private void Foo()
{
...
IsDataPickerEnabled = true/false;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.