XAML にローカル リソースがあり、それをコードの他の部分で使用したいと考えています。「グローバル」(つまり、アプリケーション全体のリソース) にするにはどうすればよいですか? これが私のローカルリソースです:
<ResourceDictionary >
<local:BoolToLightConvertor x:Key="LightConverter" / >
</ResourceDictionary>
これを App.xaml に入れるにはどうすればよいですか?
アプリケーションリソース要素またはウィンドウのレベルでリソースを定義することに加えて、特定のアプリケーションのすべてのオブジェクトがアクセスできるリソースを定義できます。次に示すように、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>
次のようにファイル(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に関する別の質問で推奨されています。残念ながら、リンクは今ではわかりません)