我正在做一個專案,目前遇到以下錯誤:每當我嘗試為日期的背景著色時,它都不起作用。XAML 示例有效,但是當我以編程方式嘗試時,它顯示錯誤。
這是 XAML 代碼:
<Calendar x:Name="calendar">
<Calendar.CalendarDayButtonStyle>
<Style TargetType="CalendarDayButton">
<Style.Triggers>
<DataTrigger Binding="{Binding Date}" Value="10/15/2022">
<Setter Property="Background" Value="Blue"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Calendar.CalendarDayButtonStyle>
</Calendar>
它確實顯示了 15.10.2022 日期藍色。
但是當我嘗試以編程方式執行此操作時,我會這樣做:
Dictionary<string, Color> dates = new Dictionary<string, Color>
{
{ "10/15/2022", Colors.Blue }
};
Style style = new Style(typeof(CalendarDayButton));
foreach (KeyValuePair<string, Color> item in dates)
{
DataTrigger trigger = new DataTrigger()
{
Value = item.Key,
Binding = new Binding("Date")
};
trigger.Setters.Add(new Setter(Control.BackgroundProperty, new SolidColorBrush(item.Value)));
style.Triggers.Add(trigger);
}
calendar.CalendarDayButtonStyle = style;
它說:'CalendarDayButton' TargetType 與元素'CalendarButton'的型別不匹配”
以編程方式將其設定為 CalendarButton 對日歷沒有任何作用。
我怎樣才能將它用作一種風格?
另外,有沒有其他方法可以做到這一點?我一直試圖讓它作業幾天但沒有解決方案。我還嘗試了其他一些 stackOverflow 主題,但有些來自舊版本的 .net 框架
我只是想讓它看起來像這樣(假設藍色是背景)
uj5u.com熱心網友回復:
您必須設定TargetType:Style
Style style = new Style()
{
TargetType = typeof(CalendarDayButton)
};
然后你的代碼應該可以作業,即只需用Style style = new Style(typeof(CalendarDayButton));上面的代碼替換。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/516395.html
標籤:C#wpf
