【问题标题】:Binding multiple properties to different sources将多个属性绑定到不同的源
【发布时间】:2012-03-03 00:02:45
【问题描述】:

我的绑定:

祖先的 DataContext :

   detailsPanel.DataContext = client 

项目控制:

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

项目模板

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

项目绑定到 Peers 集合,每个文本块绑定到当前 Peer 的名称。

我遇到的问题是我需要将每个按钮(项目)绑定到客户端中的不同属性 集合中当前 Peer 之外的“InConversation”。

这样的绑定怎么做?

【问题讨论】:

    标签: c# wpf data-binding


    【解决方案1】:

    解决方法有多种,一种是使用RelativeSource绑定:

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

    当然,只有在 ItemsControl 中使用 DataTemplate 时它才会起作用。

    一种更好的方法是使用所谓的DataContextSpy(info 和more info)直接绑定到另一个控件的DataContext。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-05-26
      • 2018-08-08
      • 2012-10-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-28
      相关资源
      最近更新 更多