我的绑定:
祖先的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的名称。
我遇到的问题是,我需要将每个按钮(项)绑定到客户端中的不同属性"InConversation"。
这样的装订怎么能完成?
有多种解决方案,一种是使用RelativeSource绑定:
<DataTemplate x:Key="PlayersItemsControlTemplate" >
<Button Content="{Binding Name}"
IsEnabled="{Binding Path=DataContext.InConversation,
RelativeSource={RelativeSource AncestorType=ItemsControl}}"></Button>
</DataTemplate>
当然,只有当您在ItemsControl
中使用DataTemplate
时,它才会起作用。
一种更好的方法是使用所谓的DataContextSpy
(信息和更多信息)直接绑定到另一个控件的DataContext
。