2009-03-04 19 views
2

Silverlight XAMLでは、ネストされたコンテナのDataContext宣言が親コンテナのDataContextを基準にしていることに気付きました。あなたはすべて確認していただけますか?Silverlight - XAMLの相対DataContext?

もしそうなら、子供XAMLコンテナ要素(つまりStackPanel)で、その相対DataContextツリーからどのように飛び出し、より高い場所で開始するか、別のDataContextを一緒に開始するStackPanelのDataContextを別のルートコンテキストに設定する必要がある場合は、

つまり、子DataContextを親DataContextから解放する方法はありますか?

(XAMLコードソリューション/構文を探して)

答えて

3

あなたの最初のassumnptionは正しいです。 DataContextは、 ネストされた要素によって継承されたものです。

子XAMLコンテナ要素では、DataContextの内容をいつでも再定義できます。

以下の例を参照してください:

 

    <UserControl.Resources> 
     <local:Customer x:Key="Cust"> 
     <local:Supplier x:Key="Supp"> 
    </UserControl.Resources> 
    <Grid x:Name="LayoutRoot" Background="White" DataContext="{StaticResource Cust}"> 
     <Grid.RowDefinitions> 
      <RowDefinition></RowDefinition> 
      <RowDefinition></RowDefinition> 
     </Grid.RowDefinitions> 
     <StackPanel Orientation="Horizontal" Grid.Row="0"> 
      <TextBlock Text="Customer Name: " /> 
      <TextBox Text="{Binding Path=Name}"/> 
     </StackPanel> 
     <StackPanel Orientation="Horizontal" Grid.Row="1" DataContext="{StaticResource Supp}"> 
      <TextBlock Text="Supplier Name: " /> 
      <TextBox Text="{Binding Path=Name}"/> 
      <TextBlock Text=" Telephone: " /> 
      <TextBox Text="{Binding Path=Telephone}"/> 
     </StackPanel> 
    </Grid> 
 

そして、ここでは、上記の例のための「モデル」クラスです:

 

    public class Customer 
    { 
     public Customer() 
     { 
      Name = "Customer name"; 
      Address = "Customer address"; 
     } 
     public string Name { get; set; } 
     public string Address { get; set; } 
    } 

    public class Supplier 
    { 
     public Supplier() 
     { 
      Name = "Supplier name"; 
      Address = "Supplier address"; 
      Telephone = "(555)555-5555"; 
     } 

     public string Name { get; set; } 
     public string Address { get; set; } 
     public string Telephone { get; set; } 
    } 
 
+0

あなたの例では、XAMLでオブジェクトを作成します。私のオブジェクトは、コンストラクタでインスタンス化されます。したがって、XAMLのUserControl.Respourcesにないため、各オブジェクトをポイントするためにXAMLが使用するもの。 – MattSlay

+0

さらに、永続バインディングが必要です。 MattSlay

+0

XAMLオプションを使用しない場合は、 クラスを作成して、他のクラスのインスタンスを次のように公開することができます。公共財産。 この「プレゼンター」を「LayoutRoot」にバインドし、他の要素のソースとしてプロパティー「 」を使用します。 – Klinger

関連する問題