How do we bind to the parent / sibling of the current datacontext (i.e., to the original property representing the current datacontext)?
I'm not talking about binding to a parent control property (in this case we are talking about the parent object, not the source) - and this can easily be done using RelativeSourceMode = FindAncestor.
RelativeSourceMode = PreviousData provides limited support for binding to the previous sibling of a data item, but not to parents or other siblings.
Dummy example:
(suppose the INPC is in place)
How to bind ItemsSource ComboBox with Departments ViewModel property?
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>
source share