2015-10-16 167 views
2

我在下面有下面的代碼。 WordListWordObservableCollection顯式設置ItemTemplate的Datacontext

我試圖完成的事情是將每個項目的DataContext設置爲包裝類NewWordViewModel而不是默認設置的Word對象。 CorrespondingWordNewWordViewModel的依賴項屬性。

問題是XAML代碼創建一個NewWordViewModel,並將其設置爲DataContext,但不會將CorrespondingWord屬性設置爲實際Word對象。

是否有xaml方法來設置此屬性?

<ItemsControl ItemsSource="{Binding WordList}"> 
    <ItemsControl.ItemTemplate> 
     <DataTemplate> 
      <ui:NewWord> 
       <ui:NewWord.DataContext> 
        <viewModels:NewWordViewModel CorrespondingWord="{Binding}"/> 
       </ui:NewWord.DataContext> 
      </ui:NewWord> 
     </DataTemplate> 
    </ItemsControl.ItemTemplate> 
</ItemsControl> 
+0

那豈不是更簡單的移動'CorrespondingWord'財產到NewWord控件並刪除NewWordViewModel? – Clemens

+0

好的,如果我將'NewWordViewModel'的所有內容移動到'NewWord'包括這些命令,這個就行得通了。但是,我現在怎樣才能爲命令編寫測試? ViewModel的目的是解耦類和啓用單元測試。 –

回答

2

您可以使用代理來保存在每個項目中隱含DataContext,並設置綁定到通常情況下,像這樣:

<ItemsControl ItemsSource="{Binding WordList}"> 
    <ItemsControl.ItemTemplate> 
    <DataTemplate> 
     <Border> 
     <Border.Resources> 
      <DiscreteObjectKeyFrame x:Key="proxy" Value="{Binding}"/> 
     </Border.Resources> 
     <ui:NewWord> 
      <ui:NewWord.DataContext> 
      <viewModels:NewWordViewModel 
        CorrespondingWord="{Binding Value, Source={StaticResource proxy}}"/> 
      </ui:NewWord.DataContext> 
     </ui:NewWord> 
     </Border> 
    </DataTemplate> 
    </ItemsControl.ItemTemplate> 
</ItemsControl> 
+0

我得到以下錯誤:'找不到目標元素的控制FrameworkElement或FrameworkContentElement。 BindingExpression :(無路徑);的DataItem = NULL;目標元素是'DiscreteObjectKeyFrame'目標屬性是'Value'(類型'Object')'。如果我使用[this]的BindingProxy類(http://www.thomaslevesque.com/2011/03/21/wpf-how-to-bind-to-data-when-the-datacontext-is-not-inherited/ )鏈接,繼承自'FrameworkElement'而不是Freezable,它不會輸出錯誤,但UI上的所有字段都是空的。有沒有一種方法可以調試哪些依賴屬性沒有設置? –

+0

實際上'x:Key =「proxy」Value =「{Binding}」'部分的綁定不起作用。如果我寫了'Value =「Some Text」'並用'

+0

@ qqww2看到我的編輯,實際上代理應該放在根視覺的「資源」中,而不是「DataTemplate的資源」。 –