繁体   English   中英

从Codebehind读取样式XAML

[英]Reading Style XAML from Codebehind

例如,我的资源文件名为theme.xaml

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
  <Color x:Key="TitleColor1">#e0e0e0</Color>
  <Color x:Key="TitleColor2">#616161</Color>
  <Color x:Key="TitleColor3">#404040</Color>
  <Color x:Key="TitleColor4">#bfbfbf</Color>
  <Color x:Key="TitleColor5">#7d0000</Color>
</ResourceDictionary>

我想阅读这些元素并将其设置在Custom对象中。

public class ThemeModel
{
    public string Key { get; set; }

    public string ColorString { get; set; }
}

最好的方法是什么?

你可以做

Color c = (Color)FindResource("TitleColor1");

那么您可以将c强制转换/转换为字符串或任何您想要的东西。

有关MSDN上的 FindResource的更多信息

我不知道为什么当您可以将ResourceFile加载到ResourceDictionary对象中时为什么要使用自定义类

        FileStream fs = new FileStream("Dictionary1.xaml", FileMode.Open);
        ResourceDictionary dictionary = (ResourceDictionary)XamlReader.Load(fs);

拥有字典对象后,您可以使用任意键和值。

您可以通过加载资源字典来访问资源字典元素。之后,可以使用资源字典中的键来访问元素。

 var s = System.Windows.Application.LoadComponent(new Uri("URI for ResourceDictionary", UriKind.Relative)) as ResourceDictionary;
        var color = s["TitleColor1"] as Color;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM