简体   繁体   中英

Using XAML style on CodeBehind

Guys im trying to using a style from Style.xaml into my code behind on my style i have a code like this

file Style.xaml

<SolidColorBrush x:Key="FontGrey" Color="#FFC5C0C0"></SolidColorBrush>  

and on my Apptest.xaml.cs file i have code like this

txt.Foreground =  new SolidColorBrush(Color.FromArgb(255, 252, 147, 25));

if i want to change my foreground color base on style.xaml how can i do that? i was trying using resources but it doesnt work

note: Style.xaml and Apptest.xaml are separated

您可以使用以下语法在Silverlight中访问定义的资源:

txt.Foreground = (SolidColorBrush)Application.Current.Resources["FontGrey"];

You can put your style into Window.Resources in Apptest.xaml like this:

    <ResourceDictionary >
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary 
              Source="Style1.xaml">
            </ResourceDictionary>
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>

Then in window code behind file Apptest.xaml.cs you can access to resource:

    InitializeComponent();
    txt.Foreground = Resources["FontGrey"] as SolidColorBrush;

如果假定资源可用,那么此代码将为您工作:

txt.Foreground = (Brush)FindResource("FontGrey");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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