簡體   English   中英

引用另一個xaml文件中定義的自定義資源

[英]Reference custom resource defined in another xaml file

我試圖在一個xaml文件中創建一個新資源,並在另一個xaml文件中引用它。 即我定義

<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文件中使用它

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

但是我收到錯誤“找不到StaticResource引用'TileBrush'。” 我可以從同一個xaml文件引用該資源,但不知道如何從另一個文件中執行此操作。

在WPF中,資源引用用作樹。 每個控件都有資源,子控件可以訪問父資源。 全局應用程序資源字典位於App.xaml文件中。 在此文件中,您可以將多個資源字典包含為合並字典。 請參閱此代碼示例:

<?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文件夾中。 並且看起來像這樣:

<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)中定義的每個字典鍵或數據模板都可以在項目的任何位置引用。 希望這可以幫助...

您應該在app.xaml文件中定義它。 這些資源在整個項目中共享

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM