rudeboy rudeboy - 1 month ago 12
C# Question

How do I access navigation properties through XAML-based databinding?

I'm attempting to learn WPF and MVVM and struggling with some databinding at the moment. I have a ComboBox that contains an observable collection of Projects, and a TextBox which is bound to the SelectedItem of the ComboBox and displays an EmployeeID value. I want to instead display the employee name that corresponds to the EmployeeID value, via a navigation property if possible, but not sure how to modify the XAML to allow for that.

public class Project
{
public int ProjectID;
public string ProjectName;
public int EmployeeID;
public Employee Emp;
}

public class Employee
{
public int EmployeeID;
public string EmployeeName;
}


MainView XAML

<ComboBox x:Name="cbxProjects" Width="75" Height="20"
ItemsSource="{Binding Projects}"
SelectedValue="{Binding Path=SelectedProject}"
DisplayMemberPath="ProjectName" />

<TextBox x:Name="tbxEmployee" Height ="20" Width="100" BorderThickness="1"
Text="{Binding Path=SelectedProject.EmployeeID}"/>


MainViewModel

private ObservableCollection<Project> _projects;
private Project _selectedProject;

public ObservableCollection<Project> Projects
{
get { { return _projects; } }
}

public Project SelectedProject
{
get { return _selectedProject; }
set
{
if (_selectedProject != value)
{
_selectedProject = value;
NotifyPropertyChanged("SelectedProject");
}
}
}

Answer

Wouldn't you just bind to Path=SelectedProject.Emp.EmployeetName instead?