2013-04-02 83 views
16

我是WPF的新手,我試圖在一個xaml文件中創建一個新資源,並在另一個xaml文件中引用它。 即我定義WPF在另一個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> 

,並試圖通過

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

但是我得到的錯誤使用它在另一個XAML文件「的StaticResource引用‘的TileBrush’沒有被發現。」 我可以從同一個xaml文件引用資源,但不知道如何從另一個文件中執行此操作。

在此先感謝。

+0

http://blogs.msdn.com/b/wpfsldesigner/archive/2010/06/03/creating-and-consuming-resource-dictionaries-in-wpf-and-silverlight.aspx –

回答

23

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

+0

正是我需要的。輝煌。謝謝。 – user1400716

+0

有一個'Resource Dictionary'的模板。我在「Windows Store Group」的「添加新項目」對話框中找到了它。 –

+1

是的,而且,如果您使用Blend模板添加資源字典,它也會創建合併的字典... –

0

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

相關問題