簡體   English   中英

DatePicker觸發WPF

[英]DatePicker Triggers WPF

以下是錯誤的,但顯示了我要執行的操作。 我有一個標簽和一個DatePicker。 日期時間? 綁定是可以為null的,因此DatePicker可以接收null值。

綁定DateTime嗎? 可以正常工作,但是如果DatePicker具有非null值,我希望Label的前景色可以更改(在Xaml中)。 我相信這是使用觸發器完成的,但這是我第一次使用觸發器。

binding to: public DateTime? NewLeadDateActiveJob


<Label  Style="{StaticResource LabelStyle}"  Grid.Row="11"  Content="New Lead:">
                <Label.Triggers>
                    <Trigger Property="{Binding ElementName=NewLeadDateActiveJobDatePicker, Path=HasValue}">
                        <Setter Property="Foreground" Value="HotPink"/>
                    </Trigger>
                </Label.Triggers>
            </Label>
<DatePicker x:Name="NewLeadDateActiveJobDatePicker" Grid.Row="11" Margin="3" HorizontalAlignment="Left" Grid.Column="1"
                        SelectedDate="{Binding objActiveJobClass.NewLeadDateActiveJob, Mode=TwoWay, NotifyOnValidationError=true, ValidatesOnExceptions=true}" 
                        Style="{StaticResource DatePickerStyle}" 
                        CalendarStyle="{StaticResource styleCalendar}">
            </DatePicker> 

我使用IValueConverter解決了該問題,但我想聽聽是否有更好的方法。

public class NullableDateTimeToColorConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value == null || value.ToString() == string.Empty)
        {
            return "Gray";
        }

        DateTime? dateTime = value as DateTime?;
        if (dateTime == null)
        {
            return "Gray";
        }

        return "Green";
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

您可以使用DataTriggers做到這一點,絕對不需要轉換器:

<Label Grid.Row="11"  Content="New Lead:">
    <Label.Style>
        <Style TargetType="{x:Type Label}" BasedOn="{StaticResource LabelStyle}">
            <Setter Property="Foreground" Value="Green" />
            <Style.Triggers>
                <DataTrigger Binding="{Binding ElementName=NewLeadDateActiveJobDatePicker, Path=SelectedDate}" Value="{x:Null}">
                    <Setter Property="Foreground"  Value="Gray" />
                </DataTrigger>
                <DataTrigger Binding="{Binding ElementName=NewLeadDateActiveJobDatePicker, Path=SelectedDate}" Value="">
                    <Setter Property="Foreground"  Value="Gray" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Label.Style>
</Label>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM