XAML 如何更改WPF DatePicker中某些元素的大小

sr4lhrrt  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(123)

我正在写一个C# WPF应用程序。
在一个窗口中,我放了两个DatePicker对象:我能够放大日历的字体和放大图像图标。
我还需要放大日历的前两行(月+年)和一周中的天数(见图..)的字体。

我为DatePicker控件创建了样式的副本,但没有标识要在其中更改的元素。我为CalendarDayButton,CalendarDayButton,CalendarItem定义了一个新的setter来设置字体为36px,但我没有看到结果。
请问如何才能做到这一点?

gcuhipw9

gcuhipw91#

让我向您展示一种使用VisualTreeHelper的方法。
首先,您需要有一种通过VisualTree搜索控件的方法。

public static IEnumerable<T> FindChildren<T>(DependencyObject parent)
    where T : DependencyObject
{
    for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
    {
        DependencyObject child = VisualTreeHelper.GetChild(parent, i);

        if (child is T childAsT)
        {
            yield return childAsT;
        }

        foreach (T grandChild in FindChildren<T>(child))
        {
            yield return grandChild;
        }
    }
}

然后,在DatePickerCalendarOpened事件处理程序中,我们可以找到Popup及其内部的控件。Popup.Child是一个Calender控件,其中包含50个TextBlock。索引为1到7的项是表示一周中的天数的TextBlocks

private void DatePickerControl_CalendarOpened(object sender, RoutedEventArgs e)
{
    if (FindChildren<Popup>(DatePickerControl).FirstOrDefault() is not Popup popup)
    {
        return;
    }

    double fontSize = 20;

    if (FindChildren<Button>(popup.Child)
        .Where(x => x.Name == "PART_HeaderButton")
        .FirstOrDefault() is Button headerButton)
    {
        headerButton.FontSize = fontSize;
    }

    if (FindChildren<TextBlock>(popup.Child) is IEnumerable<TextBlock> textBlocks)
    {
        int targetChildIndex = 1;

        for (int i = 0; i < 7; i++)
        {
            TextBlock dayOfTheWeedTextBlock = textBlocks.ElementAt(targetChildIndex);
            dayOfTheWeedTextBlock.FontSize = fontSize;
            var text = dayOfTheWeedTextBlock.Text;
            targetChildIndex++;
        }
    }

    if (FindChildren<Grid>(popup.Child)
        .Where(x => x.Name == "PART_YearView")
        .FirstOrDefault() is Grid yearViewGrid)
    {
        foreach (CalendarButton calendarButton in FindChildren<CalendarButton>(yearViewGrid))
        {
            calendarButton.FontSize = fontSize;
        }
    }

    if (FindChildren<Button>(popup.Child)
        .Where(x => x.Name == "PART_NextButton")
        .FirstOrDefault() is Button nextButton)
    {
        nextButton.RenderTransform = new ScaleTransform(1.5, 1.5);
        nextButton.RenderTransformOrigin = new Point(0.5, 0.5);
    }

}

相关问题