Defining and using resources from code and xaml

萝らか妹 提交于 2019-12-13 04:19:35

问题


I am trying to define Colors, Brushes and few others as a system resource and use them later from code and xaml like I have defined strings in AppResources.resx and used them in code like

MyApp.Resources.AppResources.MyStringResource

and in xaml like

Text="{Binding Source={StaticResource LocalizedStrings}, Path=LocalizedResources.MyStringResource}"

I came across ResourceDictionary at few places while I was looking for a solution to it. But I didn't get to know how and where to add a ResourceDictionary

I tried adding it inside App.xaml like this:

<Application.Resources>
        <ResourceDictionary>
            <local:LocalizedStrings xmlns:local="clr-namespace:DataBoundApp1" x:Key="LocalizedStrings"/>
            <SolidColorBrush Color="#FF0000" x:Key="ErrorColor"></SolidColorBrush>
        </ResourceDictionary>
</Application.Resources>

But I don't know how to use it from Code and xaml. Also are there any other ways or places where I can add a ResourceDictionary or any other thing to be used again and again later.

Please Help!


回答1:


I came across lots of solutions when am trying to achieve this and finally got the best solution. Just follow below steps.

First create a folder called Themes inside your project and add an class file in it. Name the class file called Generic.xaml, replace the existing C# code and add the following files in to it.

<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">    
<SolidColorBrush Color="#FF0000" x:Key="ErrorColor"></SolidColorBrush>
</ResourceDictionary>

And rebuild the project. Then add the following lines of code inside App.xaml.

<Application.Resources>
   <ResourceDictionary>
       <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="/Themes/Generic.xaml"/>
       </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>

Finally apply the style wherever you want in your project like this,

<TextBlock Text="Hello" Foreground="{StaticResource ErrorColor}"/>

Add the styles you want in Generic.xaml and call those styles in your project.




回答2:


You can use the solidColorBrush in xaml like so:

<Border BorderThickness="1"
        BorderBrush="{StaticResource ErrorColor}">
</Border>

See link for more details on using Application Resources

See here for a more in depth look at Xaml resources in general

EDIT

In code behind, although I wouldn't advise this as there is more room for error you would do:

SolidColorBrush = this.FindResource("ErrorColor") as SolidColorBrush;


来源:https://stackoverflow.com/questions/24889896/defining-and-using-resources-from-code-and-xaml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!