我在XAML中有一個本地資源,我希望它被代碼的其他部分使用。我怎樣才能使它成爲「全球」(即應用範圍內的資源)?這裏是我的本地資源:將WPF本地資源轉換爲應用程序資源
<ResourceDictionary >
<local:BoolToLightConvertor x:Key="LightConverter"/>
</ResourceDictionary>
我怎樣才能把它放在App.xaml中?
我在XAML中有一個本地資源,我希望它被代碼的其他部分使用。我怎樣才能使它成爲「全球」(即應用範圍內的資源)?這裏是我的本地資源:將WPF本地資源轉換爲應用程序資源
<ResourceDictionary >
<local:BoolToLightConvertor x:Key="LightConverter"/>
</ResourceDictionary>
我怎樣才能把它放在App.xaml中?
創建一個文件(例如,SharedResources.xaml)如下:
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:Your.Namespace.Here;assembly=Your.Assembly.Here">
< local:BoolToLightConvertor x:Key="LightConverter"/>
</ResourceDictionary>
在你App.xaml中加入下面幾行:
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="SharedResources.xaml" />
</ResourceDictionary.MergedDictionaries>
<Style TargetType="{x:Type Rectangle}" />
</ResourceDictionary>
</Application.Resources>
現在,您可以使用該轉換器從XAML
(該<Style TargetType="{x:Type Rectangle}"/>
內是一個解決方法,以停止WPF錯誤忽略你的資源字典,並建議在這裏SO另一個問題。不幸的是,這個鏈接現在迴避了我)
應用程序資源 除了在元素或窗口級別定義資源之外,您還可以定義特定應用程序中所有對象都可訪問的 資源。您可以通過打開App.xaml文件(對於C#項目)或Application.xaml文件 (對於Visual Basic項目)並將資源添加到Application.Resources集合來創建應用程序 資源,如 所示:
<Application x:Class="WpfApplication.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
StartupUri="Window1.xaml">
<Application.Resources>
<SolidColorBrush x:Key="appBrush" Color="LightConverter" />
</Application.Resources>
</Application>
你在這裏添加你的內置resouse(solidcolorbrush),而是我想添加我自己的類,這是BoolToLightConvertor,該怎麼做? – shd
缺少資源? – noonand
不是在本地或全局聲明轉換器,而是從擴展標記導出轉換器並將其用於所需的任何位置。看到這篇文章,例如http://www.codeproject.com/Articles/55715/WPF-Where-to-put-value-converters –