我想设置 WPF 日历的 BlackoutDates 样式。默认可视化是日期数字上方的灰色十字。例如,如何仅将它们灰显?
最佳答案
给你
<Calendar>
<Calendar.CalendarDayButtonStyle>
<Style TargetType="CalendarDayButton" BasedOn="{StaticResource {x:Type CalendarDayButton}}">
<Style.Triggers>
<Trigger Property="IsBlackedOut" Value="True">
<Setter Property="Background" Value="LightGray"/>
</Trigger>
</Style.Triggers>
</Style>
</Calendar.CalendarDayButtonStyle>
<Calendar.BlackoutDates>
<CalendarDateRange Start="24-June-2014" End="25-June-2014"/>
</Calendar.BlackoutDates>
</Calendar>
我为 CalendarDayButtonStyle
指定了自定义样式,并在该样式中在 IsBlackedOut
上定义了一个触发器,并将 Background
设置为 浅灰色
结果
您可以根据需要选择操作其他属性
消除现有的停电
要消除现有的中断,您可以选择为日历日按钮定义自定义模板,但缺点是您必须为每个主题(例如 Luna、Classic 等)维护它
我将提出一个解决方案,帮助您利用现有模板,因此无需担心此类问题
我使用了相同的附加属性
日历助手类
namespace CSharpWPF
{
class CalenderHelper : DependencyObject
{
public static bool GetIsBlackOutDisabled(DependencyObject obj)
{
return (bool)obj.GetValue(IsBlackOutDisabledProperty);
}
public static void SetIsBlackOutDisabled(DependencyObject obj, bool value)
{
obj.SetValue(IsBlackOutDisabledProperty, value);
}
// Using a DependencyProperty as the backing store for IsBlackOutDisabled. This enables animation, styling, binding, etc...
public static readonly DependencyProperty IsBlackOutDisabledProperty =
DependencyProperty.RegisterAttached("IsBlackOutDisabled", typeof(bool), typeof(CalenderHelper), new PropertyMetadata(false, OnIsBlackOutDisabledChanged));
private static void OnIsBlackOutDisabledChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
CalendarDayButton dayButton = d as CalendarDayButton;
if (dayButton.IsLoaded)
{
SetBlackout(dayButton, (bool)e.NewValue);
}
else
{
dayButton.Loaded += (s, ee) =>
{
SetBlackout(dayButton, (bool)e.NewValue);
};
}
}
static void SetBlackout(CalendarDayButton dayButton, bool collapsed)
{
ControlTemplate template = dayButton.Template;
Path blackoutPath = template.FindName("Blackout", dayButton) as Path;
if (collapsed)
blackoutPath.Visibility = System.Windows.Visibility.Collapsed;
else
blackoutPath.Visibility = System.Windows.Visibility.Visible;
}
}
}
我创建了一个带有附加属性IsBlackOutDisabled
的类CalenderHelper
,它将隐藏现有模板中的停电元素
xaml
<Calendar x:Name="cal" xmlns:l="clr-namespace:CSharpWPF">
<Calendar.CalendarDayButtonStyle>
<Style TargetType="CalendarDayButton" BasedOn="{StaticResource {x:Type CalendarDayButton}}">
<Style.Triggers>
<Trigger Property="IsBlackedOut" Value="True">
<Setter Property="Background" Value="LightGray"/>
<Setter Property="l:CalenderHelper.IsBlackOutDisabled" Value="True"/>
</Trigger>
</Style.Triggers>
</Style>
</Calendar.CalendarDayButtonStyle>
<Calendar.BlackoutDates>
<CalendarDateRange Start="24-June-2014" End="25-June-2014"/>
</Calendar.BlackoutDates>
</Calendar>
我已在触发器中启用了新创建的属性 l:CalenderHelper.IsBlackOutDisabled
,这反过来将隐藏默认的黑屏视觉效果
结果
这种方法使其能够灵活用于多种用途,您可以将其编码为其他复杂的功能,而这些功能通过简单的 xaml 不容易实现
关于wpf - 如何设置 WPF 日历中 BlackoutDates 的样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24451942/