2012-03-05 27 views
3

私はユーザーコントロールを持っており、リソース辞書を使用しています。そのユーザーコントロールには、同じリソース辞書を使用する別のユーザーコントロールがあります。私が知りたいのは、wpfが実際にそれを2回読み込んでいるかどうかであり、そうであればパフォーマンスに影響があります。これを行うためのより良い方法はありますか?ユーザー辞書のリソース辞書

ありがとうございます。

答えて

1

興味深い質問です。私は調査するために十分に興味を持った。 WPFは、要素の外観ごとに新しいResourceDirectionary(および定義されたすべてのリソースと使用される辞書)を読み込むように見えます。

のViewModel:

public class Person 
{ 
    public string name { get; set; } 
    public int age { get; set; } 
    public Person() { } 
} 

リソース(Dictionary1.xaml):

<ResourceDictionary 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:so="clr-namespace:SO" 
    > 
    <so:Person x:Key="m" name="Methuselah" age="969" /> 
</ResourceDictionary> 

ビュー:

<Window 
    x:Class="SO.MainWindow" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:so="clr-namespace:SO" 
    Height="200" Width="300" 
    Title="SO Sample" 
    > 
    <Window.Resources> 
     <ResourceDictionary Source="Dictionary1.xaml" /> 
    </Window.Resources> 

    <StackPanel DataContext={StaticResource m}> 
     <UserControl> 
      <UserControl.Resources> 
       <ResourceDictionary Source="Dictionary1.xaml" /> 
      </UserControl.Resources> 
      <TextBlock x:Name="inner" DataContext="{StaticResource m}" Text="{Binding Path=name}" /> 
     </UserControl>   
     <TextBlock x:Name="outer" Text="{Binding Path=name}" />   
     <Button Click="Button_Click">Change</Button>   
    </StackPanel> 
</Window> 

入れ

次のコードを見てみましょうペースでのブレークポイントon()コンストラクタを呼び出し、オブジェクトが2回インスタンス化されることに注意してください。または、INotifyPropertyChangeを実装する人を作り、Button_Clickために次のコードを追加します。

private void Button_Click(object sender, RoutedEventArgs e) { 
    Person innerPerson = this.inner.DataContext as Person; 
    Person outerPerson = this.outer.DataContext as Person; 
    innerPerson.name = "inner person"; 
    outerPerson.name = "outer person"; 
} 

あなたは、各リソースの単一のインスタンスを持つようにしたい場合は、app.xamlファイルの要素でreousrcesを持っています。