引用另一个xaml文件中定义的自定义资源 [英] Reference custom resource defined in another xaml file

查看:371
本文介绍了引用另一个xaml文件中定义的自定义资源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在一个xaml文件中创建一个新资源,并在另一个xaml文件中引用它. 即我定义

I am trying to create a new resource in one xaml file and reference it in another xaml file. i.e I define

<Window.Resources>
    <ImageBrush x:Key="TileBrush" TileMode="Tile" ViewportUnits="Absolute" Viewport="0 0 32 32" ImageSource="MyImageButton.png" Opacity="0.3">
    </ImageBrush>
</Window.Resources>

并尝试在另一个xaml文件中使用它

And attempt to use it in another xaml file by

<Grid>
    <Button Background="{StaticResource TileBrush}" Margin="5" Padding="5" FontWeight="Bold" FontSize="14">
        A Tiled Button
    </Button>
</Grid>

但是我收到错误消息未找到StaticResource引用'TileBrush'." 我可以从同一个xaml文件中引用资源,但是不知道如何从另一个文件中引用资源.

However I get the error "StaticResource reference 'TileBrush' was not found." I can reference the resource from the same xaml file but don't know how to do so from another file.

推荐答案

在WPF中,资源引用像一棵树一样工作.每个控件都有资源,子控件可以访问父级的资源.全局应用程序资源字典位于App.xaml文件中.在此文件中,您可以包括多个资源词典作为合并词典.参见以下代码示例:

In WPF, the resource references works as a tree. Each control have resource, and children control can access parent's resources. The global application resource dictionary is in the App.xaml file. In this file you can include several resource dictionaries as a Merged Dictionary. See this code sample:

<?xml version="1.0" encoding="utf-8"?>
<Application ...>
    <Application.Resources>
        <ResourceDictionary>
            <vm:ViewModelLocator x:Key="Locator" d:IsDataSource="True" />
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="View\SomeFileDictionary.xaml"/>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>
</Application>

SomeFileDictionary.xaml位于我的项目结构的View文件夹中.并且看起来像这样:

The SomeFileDictionary.xaml is located in the View folder of my project structure. And has looks like this:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                xmlns:ViewModel="clr-namespace:Cepha.ViewModel"
                xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
                ... >

<DataTemplate DataType="{x:Type ViewModel:SomeType}">
    <TextBox .../>
</DataTemplate>...

此文件(或App.xaml)中定义的每个字典键或数据模板都可以在项目的任何位置引用.希望这对您有帮助...

And each dictionary key or data template defined in this file (or App.xaml), can be referenced in any place of your project. Hope this helps...

这篇关于引用另一个xaml文件中定义的自定义资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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