2014-10-20 41 views
1

我在windows phone 8.1中有這個xaml。 我的頁面數據上下文綁定到ViewModel,即VM。 而我的listView綁定到ViewModel的Items。 並且每個列表視圖項目中的文本都綁定到ViewModel的項目文本。如何在Windows Phone 8.1的xaml中更改DataContext的父項

<Page DataContext="{Binding VM}"> 
<ListView ItemsSource="{Binding Items}"> 
    <ListView.ItemTemplate> 
     <DataTemplate> 
       <TextBox Text="{Binding Text}"/> 
       <TextBox Text="{Binding soemthing in VM}" /> 
     </DataTemplate> 
    </ListView.ItemTemplate> 
</ListView> 
</Page> 

我的問題是如何改變我的第二個文本框的父DataContext的,這樣我可以在我的視圖模型(不是我的ViewModel.Items)綁定的東西嗎?

謝謝。

+0

基本上,你不能 - WP Silverlight不支持的RelativeSource'模式= FindAncestor',很遺憾。必須使用解決方法。你想綁定什麼? (string?brush?另一個集合?) – McGarnagle 2014-10-20 18:15:05

+1

你總是可以使用依賴注入。注入到實際需要的綁定的引用到項目ViewModel – 2014-10-20 18:17:56

+0

我嘗試綁定到我的ViewModel中的RelayCommand。 AFAIK,RelayCommand應該在ViewModel中,所以我不能把它放在我的Items中。 – michael 2014-10-20 18:54:50

回答

0

如果你不介意的元素綁定,

<ListView ItemsSource="{Binding Items}"> 
    <ListView.ItemTemplate> 
     <DataTemplate> 
      <TextBox Text="{Binding Text}"/> 


      <!-- Bind the DataContext directly to the whatever element you like, in this case the page, then the Text Binding is basically the DataContext.VM_Property --> 
      <TextBlock Text="{Binding DataContext.VM_Property}" DataContext="{Binding ElementName=page}" ></TextBlock> 

     </DataTemplate> 

    </ListView.ItemTemplate> 
</ListView> 
相關問題