7

以下のように、リソース ディクショナリのリソースとしてボタン コントロールがあります。

<!--ButtonResources.xaml file-->
<ResourceDictionary 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Button x:Key="buttonResource" Content={Binding BoundText}/>
</ResourceDictionary>
<!--ButtonResources.xaml file-->

ここでは、2 つの異なる Windows .xaml ファイルの ContentControl コントロールの Content プロパティにバインドされた上記のボタン コントロールを使用します。このファイルでは、それぞれが独自のファイルを持っているため、各ウィンドウは、各ウィンドウのプロパティ値に基づいて上記のボタン コントロールを表示する必要があります。WindowDataContextContentViewModel's BoundText

<Window x:Class="TestClass1" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Window.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="ButtonResources.xaml"/>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Window.Resources>
    <Grid>
        <ContentControl Content={StaticResource buttonResource}/>
    </Grid>
</Window>

ただし、問題は、両方のウィンドウが BoundText プロパティに対して同じ値を表示することです。これは、両方の Windows で使用されるリソースからのボタン コントロールの同じインスタンスが両方の WPF ウィンドウにあることを意味します。

各 Window がリソースから個別のボタン コントロールを取得し、独自の ViewModelからプロパティの異なる値を表示するように、この問題を解決するにはどうすればよいですか?BoundText

編集:以下に 記載されている理由によりMSDN、 x:Shared="False" 属性を使用してこれを解決することはできません:

•項目を含む ResourceDictionary は、別の ResourceDictionary 内にネストしてはなりません。たとえば、既に ResourceDictionary アイテムである Style 内にある ResourceDictionary のアイテムに x:Shared を使用することはできません。

4

2 に答える 2

8

x:Shared属性を使用しようとしましたか?

<ResourceDictionary 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Button x:Shared="False" x:Key="buttonResource" Content={Binding BoundText}/>
</ResourceDictionary>

詳細については、こちらをご覧ください

これが機能しない場合は、ボタンの代わりにリソースにテンプレートを保存し、ウィンドウ内で ContentControl を使用して表示することができます。

于 2013-02-13T09:12:08.803 に答える
4

試す:

<Style TargetType="Button" x:Key="buttonResource">
    <Setter Property="Content" Value="{Binding BoundText}" />
</Style>


<Button Style="{StaticResource buttonResource}" />
于 2013-02-13T09:11:07.173 に答える