初めて WPF カスタム コントロール ライブラリ プールに足を踏み入れました。Control から派生したばかりのカスタム コントロール用に、別のソリューションでプロジェクトを作成しました。
カスタム コントロールを使用したいターゲット アプリでは動作しますが、App.xaml ファイルに参照を明示的に追加しない限り、既定のスタイルにアクセスできないようです。コントロール自体を使用できるように、xmlns プロパティを追加しました。コントロールをより自己完結型にする設定が欠けていることを願っています。したがって、ターゲットの WPF アプリでは、App.xaml のコメントの後に次の行を追加すると、すべて (関数とスタイル) が機能します。
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="MyStandardStuff.xaml" />
<!-- How do I avoid having everyone who uses the control having to add the following line?-->
<ResourceDictionary Source="/MyNewControl;component/Themes/Generic.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
カスタム コントロール ライブラリに、次の形式のスタイルを含む Generic.xaml ファイルを含む Themes フォルダーがあるとします。
<Style TargetType="{x:Type local:MyNewControl}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:MyNewControl}">
...
App.xaml に明示的な参照を追加せずに動作させる方法はありますか?
編集
プロジェクトで作成された ThemeInfo 属性を次に示します。
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
回答の詳細
ばかげたことをしたことが判明したため、この質問が再び出てくるかどうかはわかりませんが、そうなった場合に備えて...VSテンプレートを使用してWPFカスタムコントロールライブラリを作成しました。次に、コントロール クラスをコピーして、Visual Studio が作成した既定のクラスに貼り付けました。私が気付かなかったのは、VS が非常に重要なことを行う静的コンストラクターを作成したことです。これは、以下の回答へのコメントで指摘されました。静的コンストラクターは次のようになります
static MyNewControl()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(MyNewControl),
new FrameworkPropertyMetadata(typeof(MyNewControl)));
}
これが整ったら、ターゲットのリソース ディクショナリに追加したコードを削除できます。