首页 > 解决方案 > UWP RequestedTheme 在 ListView 和 ListViewItem 中不一致

问题描述

我的NowPlayFullPage有一个PlaylistControl,它基本上是一个 ListView。

<local:PlaylistControl
    x:Name="FullPlaylistControl"
    Margin="10,10,10,0"
    AllowReorder="True"
    AlternatingRowColor="False"
    Background="Transparent"
    IsNowPlaying="True"
    RequestedTheme="Dark" />

其中ItemTemplatePlaylistControl如下:

<local:PlaylistControlItem
    Data="{x:Bind}"
    DataContext="{x:Bind}"
    RequestedTheme="{Binding ElementName=PlaylistController, Path=RequestedTheme}"
    ShowAlbumText="{Binding ElementName=PlaylistController, Path=ShowAlbumText}" />

如果Loaded发生PlaylistControlItem,我调用了一个函数SetTextColor

private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
    MediaHelper.SwitchMusicListeners.Add(this);
    SetTextColor(MediaHelper.CurrentMusic);
}

public void SetTextColor(Music music)
{
    if (Data == music)
    {
        TitleTextBlock.Foreground = ArtistTextButton.Foreground = AlbumTextButton.Foreground = DurationTextBlock.Foreground =
        LongArtistTextButton.Foreground = LongArtistAlbumPanelDot.Foreground = LongAlbumTextButton.Foreground = ColorHelper.HighlightBrush;
        TextColorChanged = true;
    }
    else if (TextColorChanged)
    {
        if (RequestedTheme == ElementTheme.Dark)
        {
            TitleTextBlock.Foreground = ColorHelper.WhiteBrush;
            ArtistTextButton.Foreground = AlbumTextButton.Foreground = DurationTextBlock.Foreground =
            LongArtistTextButton.Foreground = LongArtistAlbumPanelDot.Foreground = LongAlbumTextButton.Foreground = ColorHelper.GrayBrush;
        }
        else
        {
            TitleTextBlock.Foreground = ArtistTextButton.Foreground = AlbumTextButton.Foreground = DurationTextBlock.Foreground =
            LongArtistTextButton.Foreground = LongArtistAlbumPanelDot.Foreground = LongAlbumTextButton.Foreground = ColorHelper.BlackBrush;
        }
        TextColorChanged = false;
    }
}

我的问题是,为什么RequestedTheme在被SetTextColor调用的Loaded事件中有值ElementTheme.Default而不是ElementTheme.DarkRequestTheme的什么时候PlaylistControlItem保持的值,Dark以便我的文本颜色可以正确设置?

标签: c#uwpwin-universal-app

解决方案


明智的做法是,您应该使用 XAML 中的 ThemeResource,而不是代码来处理此问题,请参阅:https ://docs.microsoft.com/en-us/windows/uwp/xaml-platform/themeresource-markup-extension

但是要回答您的问题,这是预期的行为。ElementTheme.Default仅仅意味着该元素没有覆盖它的主题并且正在使用默认的应用程序主题。其他两个值表示该元素已明确覆盖其主题。App.Current.RequestedTheme给出应用程序的实际主题。除非您在该特定元素上明确将其设置为其他值,否则FrameworkElement.RequestedTheme将始终具有值。Default它的所有孩子仍然具有价值Default

请注意,您应该比较ActualTheme,而不是RequestedTheme,因为如果它的值仍然是 ,则父级可能会导致它使用与应用程序不同的主题ElementTheme.Default

像下面这样的方法可能会帮助您获得正确的 Light/Dark 值。

public static ElementTheme GetEffectiveTheme(FrameworkElement e)
{
    if (e.ActualTheme == ElementTheme.Default)
        return App.Current.RequestedTheme == ApplicationTheme.Dark ? ElementTheme.Dark : ElementTheme.Light;

    return e.ActualTheme;
}

而且,只需使用 ThemeResources。他们会自动重新评估主题更改,无需任何代码或事件监听器。


推荐阅读