XAML 在悬停鼠标时更改ExpanderHeader背景颜色Winui 2.x UWP

slsn1g29  于 2023-09-28  发布在  其他
关注(0)|答案(1)|浏览(121)

如何在Winui 2.x中更改鼠标悬停时的ExpanderHeader背景颜色?
改变背景的方法之一是覆盖StaticResource

<StaticResource
    x:Key="ExpanderHeaderBackground"
    ResourceKey="CardBackgroundFillColorDefaultBrush" />

悬停时从代码更改不会给予任何结果:

private void Expander_PointerEntered(object sender, PointerRoutedEventArgs e)
        {
            var expander = sender as Expander;
            expander.Resources["ExpanderHeaderBackground"] = Application.Current.Resources["ApplicationPageBackgroundThemeBrush"];
        }

        private void Expander_PointerExited(object sender, PointerRoutedEventArgs e)
        {
            var expander = sender as Expander;
            expander.Resources["ExpanderHeaderBackground"] = Application.Current.Resources["CardBackgroundFillColorDefaultBrush"];
        }

我不想为这个控件重新创建整个样式,只是为了改变标题背景。
Expander源代码:https://github.com/microsoft/microsoft-ui-xaml/blob/release/2.8/dev/Expander/Expander.xaml

zrfyljdw

zrfyljdw1#

您可以直接在可视化树中设置ToggleButton元素的Background属性:

private void Expander_PointerEntered(object sender, PointerRoutedEventArgs e)
{
    var expander = sender as Expander;
    var toggleButton = GetChildOfType<ToggleButton>(expander);
    toggleButton.Background = Application.Current.Resources["ApplicationPageBackgroundThemeBrush"] as Brush;
}

private void Expander_PointerExited(object sender, PointerRoutedEventArgs e)
{
    var expander = sender as Expander;
    var toggleButton = GetChildOfType<ToggleButton>(expander);
    toggleButton.Background = Application.Current.Resources["CardBackgroundFillColorDefaultBrush"] as Brush;
}

private static T GetChildOfType<T>(DependencyObject depObj) where T : DependencyObject
{
    if (depObj == default)
        return default;

    for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
    {
        var child = VisualTreeHelper.GetChild(depObj, i);

        var result = (child as T) ?? GetChildOfType<T>(child);
        if (result != default)
            return result;
    }
    return default;
}

相关问题