【发布时间】:2011-08-11 12:15:39
【问题描述】:
我们如何绑定到当前数据上下文的父/兄弟(即表示当前数据上下文的源属性)?
我不是在谈论绑定到父控件的属性(这种情况涉及目标的父级而不是源的父级) - 这可以通过使用 RelativeSourceMode=FindAncestor 轻松完成。
RelativeSourceMode=PreviousData 对绑定到数据项的前一个同级提供有限支持,但不支持绑定到父级或其他同级。
虚拟示例:
(假设 INPC 到位)
如何将 ComboBox 的 ItemsSource 绑定到 ViewModel 的 Departments 属性?
public class Person
{
public string Name { get; set; }
public string Department { get; set; }
}
public class PersonViewModel
{
public List<Person> Persons { get; set; }
public List<string> Departments { get; set; }
public PersonViewModel()
{
Departments = new List<string>();
Departments.Add("Finance");
Departments.Add("HR");
Departments.Add("Marketing");
Departments.Add("Operations");
Persons = new List<Person>();
Persons.Add(new Person() { Name = "First", Department = "HR" });
Persons.Add(new Person() { Name = "Second", Department = "Marketing" });
Persons.Add(new Person() { Name = "Third", Department = "Marketing" });
}
}
XAML:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication1"
Title="MainWindow" Height="300" Width="300">
<Grid>
<DataGrid ItemsSource="{Binding Persons}" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Header="Name" Binding="{Binding Name}" />
<DataGridTemplateColumn>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<ComboBox ItemsSource="{Binding Departments???}"
SelectedValue="{Binding Department}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
</Grid>
</Window>
【问题讨论】:
-
所以
{Binding DataContext.Departments, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type DataGrid}}}不是你想要的? -
hmmm...没想到我可以使用父控件的DataContext属性来获取父数据项.. :).
-
为了您的方便添加了我的评论作为答案 =)
标签: wpf data-binding