![](/img/trans.png)
[英]Binding in ItemsControl not bubbling to the item from ItemsSource
[英]Binding property of item from ItemsControl to value outside of ItemsSource?
我有一个ItemsControl,并且有一个人员列表。 人员列表中的每个元素都包含人员的姓名,仅此而已。 在C#代码中,我将testItemsControl.ItemsSource设置为一个可观察的集合,其中包含每个人的姓名。 公司在后面的代码中定义。 下面的xaml代码可以正确找到名称,但是当然找不到公司。
<ItemsControl x:Name="testItemsControl">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid>
<TextBlock Text="{Binding Name}"/>
<TextBlock Text="{Binding Company}"/>
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
我如何正确绑定公司?
您必须使用RelativeSource绑定。
后面的代码。
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>
谢谢,拉尼肯特
您定义的每个DataTemplate都使用ItemsControl.ItemsSource中的一个对象作为DataContext。 在您的情况下,它是一个人类。
因此,在DataTemplate内部,它正在寻找Contents Name和Company属性。 在这种情况下,Person.Name,Person.Company。
如果要查找公司,则可以将公司属性添加到人员类,或设置绑定的路径以查找公司属性。 后者取决于您相对于itemsSource定义公司属性的位置
创建一个同时包含Name和Company的类,用新创建的类型的对象组成您的列表,并将其设置为itemssource。
internal class Worker
{
public string Name { get; set; }
public string Company { get; set; }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.