2011-06-01 39 views
4

嗨我想了解使用嵌套視圖的最佳做法。如何在WPF MVVM中使用嵌套視圖

我有一個'屬性'視圖,它綁定到視圖模型中名稱值對的集合。我需要在我的用戶界面的各個地方重複使用它。

我有另一個'條件視圖',它有一個字符串屬性和字典(字符串,字符串)集合。我試圖在XAML

<StackPanel> 
     <StackPanel Orientation="Horizontal"> 
      <Label Content="{x:Static l:StringResources.ConditionViewLabelText}" /> 
      <TextBox Text="{Binding Type,Mode=TwoWay}" Width="100" /> 
     </StackPanel> 
     <vw:AttributeView /> 
    </StackPanel> 

創建一個文本框,並添加屬性視圖控制我想將AttributeView的綁定屬性的詞典(字符串,字符串)父視圖模型的集合屬性綁定。什麼是最好的方式來做到這一點。我無法將vw:AttributeView綁定到ConditionViewModels?

你能告訴我最好的做法嗎?

- 編輯請找到我的AttributeView(這是子視圖的xaml代碼)。數據模板被綁定到一個觀察的集合在AttributeViewModel

<StackPanel> 
     <ItemsControl ItemsSource="{Binding AllAttributes}"> 
      <ItemsControl.ItemTemplate> 
       <DataTemplate> 
        <StackPanel Orientation="Horizontal"> 
         <TextBox Width="100" Text="{Binding Name, Mode=TwoWay}" Margin="5,0,5,0" /> 
         <TextBox Width="100" Text="{Binding Value, Mode=TwoWay}" Margin="5,0,5,0" /> 
         <TextBlock Width="100" Text="{Binding KeyValue, Mode=OneWay}" /> 
         <Button Width="50" Content="{x:Static l:StringResources.AttributeViewButtonDeleteText}" Command="{Binding Path=DataContext.DeleteAttribute, ElementName=AttributeControl}" CommandParameter="{Binding Name}"></Button> 
        </StackPanel> 
       </DataTemplate> 
      </ItemsControl.ItemTemplate> 
     </ItemsControl> 
     <Button Name="btnSomething" Content="{x:Static l:StringResources.AttributeViewButtonAddText}" Command="{Binding AddNewAttribute}" /> 
    </StackPanel> 
</Grid> 
+1

您需要在這裏提供更多信息,您能否請您展示您的ViewModel代碼,尤其是兩種視圖模型之間的關係。 – ColinE 2011-06-01 09:04:03

+0

嗨ColinE(感謝您的回覆),我的兩個ViewModel目前沒有任何關係。 View層次結構也應該在ViewModel層次中複製。因爲In應該在父視圖的視圖模型中有一個類型爲Child view的viewmodel類型的pulbic屬性。 – ganeshran 2011-06-01 09:43:58

+0

嘿,我的問題有一個答案,但它被刪除。奇怪:( – ganeshran 2011-06-01 09:55:15

回答

4

根據您的意見,您的父/子關係不反映在您的視圖模型,你有兩個選擇:

  1. 創建關係,以反映您視圖中的關係,如果您需要,可以從父級導航到子級,反之亦然。
  2. 使用RelativeSource FindAncestor綁定向上瀏覽可視化樹,並找到綁定到父視圖模型的控件,通過此控件DataContext

選項(2)會讓你看起來很聰明,但選項(1)要簡單得多!

+0

感謝ColinE,我會嘗試第一種方法,並回發,如果它的工作或不工作!! – ganeshran 2011-06-01 10:12:37

+0

嗨ColinE,爲實現Option1,我應該把VW:AttributeView內的項目模板,並設置數據上下文這個ItemTemplate的子Viewmodel屬性?這是一個正確的方式來實現選項1你說 – ganeshran 2011-06-01 10:36:07

+0

是的這聽起來是對我的。 – ColinE 2011-06-01 10:49:44