【问题标题】:Is it possible to convert a XAML resource dictionary style to it's c# equivalent?是否可以将 XAML 资源字典样式转换为与 c# 等效的样式?
【发布时间】:2019-11-21 08:07:16
【问题描述】:

我是 Xamarin 和 UWP 的新手 - 尽管我们使用的是 Xamarin,但这个问题是关于 UWP 的。

我有一个资源字典 .xaml 文件。我需要创建这个文件的 c# 版本(不要问为什么,说来话长)。

基本上我有一些类似的东西......

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Style TargetType="Button">
        <Setter Property="Background" Value="{ThemeResource SystemControlBackgroundBaseLowBrush}" />
        <Setter Property="Foreground" Value="{ThemeResource SystemControlForegroundBaseHighBrush}" />
        <Setter Property="BorderBrush" Value="{ThemeResource SystemControlForegroundTransparentBrush}" />
        <Setter Property="BorderThickness" Value="0,0,0,2" />
        <Setter Property="Padding" Value="12,8,12,8" />
        <Setter Property="HorizontalAlignment" Value="Left" />
        <Setter Property="VerticalAlignment" Value="Center" />
        <Setter Property="FontFamily" Value="{ThemeResource ContentControlThemeFontFamily}" />
        <Setter Property="FontWeight" Value="Normal" />
        <Setter Property="FontSize" Value="{ThemeResource TextStyleLargeFontSize}" />
        <Setter Property="UseSystemFocusVisuals" Value="False" />
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="Button">
                    <Grid x:Name="RootGrid"

...

是否有任何直接的方法可以创建与此 .xaml 文件等效的 c# 文件?

【问题讨论】:

  • 将其解析为 XML?如果你愿意,你可以为它创建一个类型化的解析器。
  • 不抱歉,我的意思是我需要创建继承自 UWP ResourceDictionary(我认为)的 ac# 类,然后添加相同的属性等。 - 创建我自己的自定义样式,但不要使用 XAML,而是使用C#。这甚至可能是不可能的,但据我所知,XAML 在幕后转换为 c# 类?谢谢

标签: c# xaml uwp


【解决方案1】:

通常在UWP中,可以在运行时获取当前加载的ResourceDictionary并修改资源。

像这样:

Application.Current.Resources["SystemAccentColor"] = Colors.Red;

如果您打算修改资源项并使其在当前页面上运行,这里有一些提示:

  • 修改的资源必须存在于当前资源字典中
  • 资源引用必须与ThemeResource一起使用

修改资源入口后,需要刷新主题才能使资源生效

if (this.RequestedTheme == ElementTheme.Light)
{
    this.RequestedTheme = ElementTheme.Dark;
    this.RequestedTheme = ElementTheme.Light;
}
else if (this.RequestedTheme == ElementTheme.Dark)
{
    this.RequestedTheme = ElementTheme.Light;
    this.RequestedTheme = ElementTheme.Dark;
}
else
{
    this.RequestedTheme = ElementTheme.Light;
    this.RequestedTheme = ElementTheme.Dark;
    this.RequestedTheme = ElementTheme.Default;
}

您可以通过修改当前的ResourceDictionary 来实现您的目标,而无需继承ResourceDictionary 类进行重写。毕竟大部分资源都是可以预定义的。

最好的问候。

【讨论】:

    【解决方案2】:

    没关系,我通过创建一个静态样式类并在静态方法中添加设置器,然后从 App.Xaml.cs 调用它来解决这个问题。

    它现在解决了我的问题。

    非常感谢您的帮助。

    【讨论】:

      猜你喜欢
      • 2017-01-18
      • 1970-01-01
      • 1970-01-01
      • 2011-12-19
      • 2020-05-19
      • 1970-01-01
      • 1970-01-01
      • 2011-01-15
      • 1970-01-01
      相关资源
      最近更新 更多