将 ItemsControl 中项目的属性绑定到 ItemsSource 之外的值? [英] Binding property of item from ItemsControl to value outside of ItemsSource?
本文介绍了将 ItemsControl 中项目的属性绑定到 ItemsSource 之外的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个 ItemsControl 和一个人员列表.人员列表中的每个元素都包含此人的姓名,而没有其他内容.在 c# 代码中,我将 testItemsControl.ItemsSource 设置为包含每个人姓名的可观察集合.公司是在代码隐藏中定义的.以下 xaml 代码正确地找到了名称,但当然没有找到公司.
I have an ItemsControl and I have a list of people. Each element in the list of people contains the person's name and nothing else. In the c# code, I set testItemsControl.ItemsSource to an observable collection that contain the name of each person. Company is defined in the code-behind. The following xaml code correctly finds the Name, but of course doesn't find the Company.
<ItemsControl x:Name="testItemsControl">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid>
<TextBlock Text="{Binding Name}"/>
<TextBlock Text="{Binding Company}"/>
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
如何正确绑定公司?
推荐答案
你必须使用 RelativeSource 绑定.
You have to use RelativeSource binding.
背后的代码.
public partial class Window3 : Window
{
public Window3()
{
InitializeComponent();
this.DataContext = this;
BuildData();
Company = "XYZ";
testItemsControl.ItemsSource = Persons;
}
private void BuildData()
{
Persons.Add(new Person() { Name = "R1" });
Persons.Add(new Person() { Name = "R2" });
Persons.Add(new Person() { Name = "R3" });
}
public string Company { get; set; }
private ObservableCollection<Person> _persons = new ObservableCollection<Person>();
public ObservableCollection<Person> Persons
{
get { return _persons; }
set { _persons = value; }
}
}
XAML 代码
<ItemsControl x:Name="testItemsControl">
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Name}" Margin="5"/>
<TextBlock Text="{Binding Company, RelativeSource={RelativeSource AncestorType={x:Type Window}}}" Margin="5" />
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
谢谢,拉吉尼坎特
这篇关于将 ItemsControl 中项目的属性绑定到 ItemsSource 之外的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文