我正在尝试比较从两个DatePicker
中选择的两个日期,如果结束日期低于开始日期,则必须禁用该按钮,这是我的xaml结构:
<DatePicker x:Name="StartDate" />
<DatePicker x:Name="EndDate" />
<Button>
<Button.Resources>
<Style TargetType="Button" BasedOn="{StaticResource ButtonStyle}">
<Style.Triggers>
<DataTrigger Value="True">
<DataTrigger.Binding>
<MultiBinding>
<MultiBinding.Converter>
<Converters:DateComparer />
</MultiBinding.Converter>
<Binding ElementName="StartDate" Path="SelectedDate"/>
<Binding ElementName="EndDate" Path="SelectedDate" />
</MultiBinding>
</DataTrigger.Binding>
<Setter Property="IsEnabled" Value="False" />
</DataTrigger>
</Style.Triggers>
</Style>
</Button.Resources>
</Button>
这是我的转换器:
public class DateComparer : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
if (values.Length < 2)
return false;
DateTime startDate = DateTime.ParseExact(values[0].ToString(),
"dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture);
DateTime endDate = DateTime.ParseExact(values[1].ToString(),
"dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture);
//La data finale è minore della data iniziale
if (endDate < startDate)
return true;
return false;
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
在values
对象上我得到了Unsect Value,为什么?
答案 0 :(得分:0)
从您的xaml判断,首次启动窗口时没有任何内容可以初始化SelectedDate
,因此它为空。我能够按原样使用xaml,但我不得不对转换器进行一些修改。
ToString()
,然后解析它们。它们已经DateTime
is
运算符。这两个都进行null
检查并在初始化期间丢弃未设置的值。以Convert
方法:
public object Convert(object[] values, Type targetType,
object parameter, CultureInfo culture)
{
bool ret = false;
if (values.Length > 1 && values[0] is DateTime && values[1] is DateTime)
{
DateTime startDate = (DateTime)values[0];
DateTime endDate = (DateTime)values[1];
ret = endDate < startDate;
}
return ret;
}