2017-06-15 53 views
0

我從WPF工具的手風琴,我綁定值更改文本塊前臺裏面的DataTemplate取決於日期勢必

<layoutToolkit:Accordion x:Name="myAccordion"> 
     <layoutToolkit:Accordion.ItemTemplate> 
      <DataTemplate> 
       <TextBlock x:Name="myHeader" Text="{Binding Date}" /> 
       <DataTemplate.Resources> 
        <local:BeforeTodayConverter x:Key="IsBeforeToday" /> 
       </DataTemplate.Resources> 
       <DataTemplate.Triggers> 
       <DataTrigger 
        Binding="{Binding Date, Converter={StaticResource IsBeforeToday}}" 
        Value="True"> 
       <Setter 
        TargetName="myHeader" 
        Property="Foreground" 
        Value="Blue" /> 
       </DataTrigger> 
       </DataTemplate.Triggers> 
      </DataTemplate> 
     </layoutToolkit:Accordion.ItemTemplate> 
     <layoutToolkit:Accordion.ContentTemplate> 
      <DataTemplate> 
       //not important 
      </DataTemplate> 
     </layoutToolkit:Accordion.ContentTemplate> 
    </layoutToolkit:Accordion> 

轉換器:

public class BeforeTodayConverter : IValueConverter 
{ 
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 
{ 
    if (!(value is DateTime)) 
    { 
     return false; 
    } 

    return ((DateTime)value).CompareTo(DateTime.Today) < 0; 
} 

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

} 我要的是改變前景文本塊「myHeader」取決於日期邊界。如果日期從今天的日期開始,我希望它是藍色的,如果日期是從今天的日期開始的,我希望它是紅色的。

有什麼辦法可以解決這個問題嗎?

回答

1

寫值轉換器來比較日期:

public class BeforeTodayConverter : IValueConverter 
{ 
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     if (!(value is DateTime)) 
     { 
      return false; 
     } 

     return ((DateTime)value).CompareTo(DateTime.Today) < 0; 
    } 

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

並使用它在模板中像這樣:

<DataTemplate> 
    <TextBlock 
     x:Name="myHeader" 
     Text="{Binding Date}" 
     Foreground="Red" 
     /> 
    <DataTemplate.Resources> 
     <local:BeforeTodayConverter x:Key="IsBeforeToday" /> 
    </DataTemplate.Resources> 
    <DataTemplate.Triggers> 
     <DataTrigger 
      Binding="{Binding Date, Converter={StaticResource IsBeforeToday}}" 
      Value="True" 
      > 
      <Setter 
       TargetName="myHeader" 
       Property="Foreground" 
       Value="Blue" 
       /> 
     </DataTrigger> 
    </DataTemplate.Triggers> 
</DataTemplate> 
+0

謝謝您的回答!我試圖實現,它似乎並沒有工作,我沒有得到任何錯誤,但標題仍然是紅色 – 281

+0

@ 281請將您的解決方案的版本添加到您的問題。 –

+0

謝謝你,我得到它的工作,我剛開始並沒有意識到,我綁定的日期是一個字符串......但現在它完美的作品! – 281