从代码和 xaml 定义和使用资源 [英] Defining and using resources from code and xaml

查看:40
本文介绍了从代码和 xaml 定义和使用资源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将颜色、画笔和其他一些资源定义为系统资源,然后在代码和 xaml 中使用它们,就像我在 AppResources.resx 中定义字符串并在代码中使用它们一样

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

和像xaml一样

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

在寻找解决方案时,我在几个地方遇到了 ResourceDictionary.但我不知道如何以及在何处添加 ResourceDictionary

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

我尝试将它添加到 App.xaml 中,如下所示:

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>

但我不知道如何从代码和 xaml 中使用它.还有其他任何方法或地方可以添加 ResourceDictionary 或任何其他可以在以后反复使用的东西.

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.

请帮忙!

推荐答案

我在尝试实现这一目标时遇到了很多解决方案,最终得到了最佳解决方案.只需按照以下步骤操作即可.

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

首先在您的项目中创建一个名为 Themes 的文件夹,并在其中添加一个类文件.将类文件命名为 Generic.xaml,替换现有的 C# 代码并将以下文件添加到其中.

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>

并重建项目.然后在 App.xaml 中添加以下代码行.

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}"/>

Generic.xaml 中添加您想要的样式并在您的项目中调用这些样式.

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

这篇关于从代码和 xaml 定义和使用资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆