2012-03-03 91 views
2

我綁定:綁定多個屬性不同來源

祖先的的DataContext:

detailsPanel.DataContext = client 

ItemsControl的:

<ItemsControl                 
      x:Name="PlayersItemsControl" 
      ItemsSource="{Binding Peers}" 
      ItemsPanel="{StaticResource PlayersItemsControlPanel}" 
      ItemTemplate="{StaticResource PlayersItemsControlTemplate}">      
    </ItemsControl>  

的itemstemplate

 <DataTemplate x:Key="PlayersItemsControlTemplate" > 
     <Button Content="{Binding Name}" IsEnabled="{Binding InConversation,Converter={StaticResource MyStatusToButtonEnableConverter}}">             </Button> 
    </DataTemplate> 

項目源:

 public class Client : INotifyPropertyChanged 
     {         
      // the itemscontrol items source 
      private ObservableCollection<Player> peers; 
      public ObservableCollection<Player> Peers 
      { 
       get 
       { 
        if (peers == null) 
         peers = new ObservableCollection<Player>(); 
        return peers; 
       } 
      } 
      // the property i wan't to bind to IsEnabled Property of the Button 
      private bool inConversation; 
      public bool InConversation 
      { 
       get {return inConversation; } 
       set 
       { 
         inConversation = value; 
         if(PropertyChanged != null) 
          PropertyChanged(this,new PropertyChangedEventArgs("InConversation")); 
       } 
      } 
     } 

項目被結合到對等體集合,並且每個文本塊被綁定到當前對等的名字。

我遇到的問題是我需要將每個按鈕(項目)綁定到客戶端 「InConversation」中的不同屬性以及集合中的當前Peer。

這樣的綁定怎麼辦?

回答

1

有多種解決方案,一種是使用RelativeSource結合:

<DataTemplate x:Key="PlayersItemsControlTemplate" > 
<Button Content="{Binding Name}" 
     IsEnabled="{Binding Path=DataContext.InConversation, 
     RelativeSource={RelativeSource AncestorType=ItemsControl}}"></Button> 
</DataTemplate> 

當然,如果你使用DataTemplate內的ItemsControl它只會工作。

一個更好的方法是使用所謂的DataContextSpyinfomore info)直接綁定到另一個控件的DataContext