简体   繁体   English

Windows应用商店应用 - XAML - C# - 在代码中访问ThemeResource

[英]Windows Store App - XAML - C# - Access ThemeResource in code

I have a Styles.xaml file where I have declared various colours and styles. 我有一个Styles.xaml文件,我已经声明了各种颜色和样式。

    <SolidColorBrush x:Key="MyColour" Color="#FFFF411E"/>

I want to access this in code, as I have control and I want to bind the background colour to a Property in an object. 我想在代码中访问它,因为我有控制权,我想将背景颜色绑定到对象中的Property。 This easily done, however, the object is created from the response to a server call and the property could be one of many colours. 但是,这很容易实现,对象是根据对服务器调用的响应创建的,属性可以是多种颜色之一。 I could define the colour in code, but as I use the same colour for other controls defined in XAML I dont really want to define the same colour twice in the application. 我可以在代码中定义颜色,但是因为我对XAML定义的其他控件使用相同的颜色,所以我真的不想在应用程序中定义相同的颜色两次。 So I want a way to be able to access the SolidColorBrush brush in code to be able to use it. 所以我想要一种能够在代码中访问SolidColorBrush画笔以便能够使用它的方法。

Any idea's how to do this? 任何想法是如何做到这一点?

试试这个..

 Application.Current.Resources[ "MyColour" ] as SolidColorBrush 

first you should have a ResourceDictionary in your xaml or in file.cs. 首先,您应该在xaml或file.cs中拥有ResourceDictionary。

xaml : <ResourceDictionary Source="Styles.xaml"/> xaml: <ResourceDictionary Source="Styles.xaml"/>

code : Resources.MergedDictionaries.Add(new ResourceDictionary { Source = new Uri(@"/" + this.GetType().Assembly.GetName().Name + ";component/" + @"Styles.xaml", UriKind.Relative) }); code: Resources.MergedDictionaries.Add(new ResourceDictionary { Source = new Uri(@"/" + this.GetType().Assembly.GetName().Name + ";component/" + @"Styles.xaml", UriKind.Relative) });

then you can access to it like this 然后你可以像这样访问它

SolidColorBrush mycolor = Resources["MyColour"] as SolidColorBrush;

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

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