如何继承或覆盖 WinUI 3 控件的默认样式的元素?

问题描述 投票:0回答:2

我正在尝试学习如何在 WinUI 3(来自 WindowsAppSDK 1.1.1)中最有效地使用样式,但我很难让简单的继承发挥作用。

考虑 NavigationViewItem 类。我想修改默认样式以绑定 FontSize 和 Height 属性。以下内容适用于我的页面 XAML:

    <NavigationViewItem x:Uid="Shell_05" helpers:NavigationHelper.NavigateTo="ViewModels._05CreditViewModel"
                        FontSize="{Binding ViewModel.RootShellFontSize, ElementName=shellPage}"
                        Height="{Binding ViewModel.CurrentMenuItemHeight, ElementName=shellPage}">
        <NavigationViewItem.Icon>
            <BitmapIcon UriSource="\Images\credit.png"/>
        </NavigationViewItem.Icon>
    </NavigationViewItem>

但是将这两个属性添加到页面资源中则不起作用(尽管 FontSize 属性在以下每个属性中都有效。但 Height 则不起作用):

<Page.Resources>
    <Style TargetType="NavigationViewItem" >
        <Setter Property="FontSize" Value="{Binding ViewModel.RootShellFontSize, ElementName=shellPage}" />
        <Setter Property="Height" Value="{Binding ViewModel.CurrentMenuItemHeight, ElementName=shellPage}" />
    </Style>
</Page.Resources>

将样式添加到资源字典并合并也不行。我已经阅读了有关继承样式的内容,并且 BasedOn="" 扩展是从 2.6 之前的 WinUI 版本中的现有样式派生的显式方法(我认为)。显然,WinUI 3 不需要 BasedOn。无论如何,简单地指定

TargetType="NavigationViewItem"
是行不通的,但

也不起作用
<Style TargetType="controls:NavigationViewItem" BasedOn="DefaultNavigationViewItemStyle">

SDK v1.1.1的源代码在generic.xaml中声明了NavigationViewItem的默认样式,但没有DefaultNavigationViewItemStyle的定义。

我也无法使用

从默认样式派生
<Style TargetType="controls:NavigationViewItem" BasedOn="{StaticResource {x:Type NavigationViewItem}}">

因为

x:Type
未定义。

我可以在代码中执行我想要的所有绑定,但我认为在 XAML 中执行此操作会更清晰、更高效。

如何在桌面应用程序中继承、派生或覆盖 WinUI 3 控件(不是自定义控件)的部分默认样式?

感谢您的帮助。指向 WinUI 3 文档(或书籍和文章)的良好 XAML 的指针也将不胜感激。

xaml inheritance winui
2个回答
1
投票

在您的情况下,高度很可能不起作用,因为 page.resources 在对象初始化之前编译,并且 CurrentMenuItemHeight 的高度为 0。要解决此问题,只需将模式设置为一种方式即可

{Binding ViewModel.CurrentMenuItemHeight,Mode=OneWay , ElementName=shellPage}

当您希望使用 BasedOn 时,只需说

BasedOn={ThemeResource styleName}
。 只需确保样式实际上是在 Generic.xaml 文件中定义的,您可以在“C:\Users\AdminName.nuget\packages\microsoft.windowsappsdk .1.1\lib\uap10.0\Microsoft.UI\Themes”中找到该样式

所以你的最终页面.资源应该是这样的:

<Page.Resources>    
<Style TargetType="NavigationViewItem" >
    <Setter Property="FontSize" Value="{Binding ViewModel.RootShellFontSize, ElementName=shellPage}" />
    <Setter Property="Height" Value="{Binding ViewModel.CurrentMenuItemHeight, Mode=OneWay, ElementName=shellPage}" />
</Style>    
</Page.Resources>

但是使用 x:Bind 而不是 Binding 会好得多。您可以查看此页面以了解更多信息https://learn.microsoft.com/en-US/windows/uwp/data-binding/data-binding-in-deep


0
投票

@aturnbul 据我所知,你被困住了。当 generic.xaml 中的样式没有 x:Key 时,就无法引用它。在某些情况下,我必须将样式复制到我自己的文件中并添加一个键,以便我可以在派生文件中引用它。这些样式也没有一致的命名。

© www.soinside.com 2019 - 2024. All rights reserved.