eran otzap
eran otzap

Reputation: 12533

Binding multiple properties to different sources

my binding:

the ancestor's DataContext :

   detailsPanel.DataContext = client 

the itemscontrol :

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

the itemstemplate

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

the items source :

        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"));
                 }
            }
        }

the items are bound to the Peers collection and each textblock is bound to the name of the current Peer .

the problem i'm having is that i need to bind each Button (item) to a different Property in Client "InConversation" in addition to the current Peer in the collection .

how can a binding like this be done ?

Upvotes: 2

Views: 576

Answers (1)

nemesv
nemesv

Reputation: 139758

There are multiple solutions, one is to use RelativeSource binding:

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

Of course it will only work if you use your DataTemplate inside an ItemsControl.

One better approach is to use a so called DataContextSpy (info and more info) to bind directly to another control's DataContext.

Upvotes: 1

Related Questions