I use VS2013, WPF 4.5, Caliburn Micro 2.0.2. This is a sample project of mine. My ShellViewModel has base class Conductor and has collection of model (a property) called Vehicles. I created also ChildViewModel that has base class Screen and a property called ParentVm, which contains its parent. In my real project I have surely more than one child viewmodel (thus, > 1 screens)
The model (class Vehicle) contains properties: Manufacturer, Model and Type.
How can I bind DisplayMemberPath of ListBox in ChildView which has ItemsSource="ParentVm.Vehicles", so the ListBox can show the Manufacturer of class Vehicle?
Following is my sample code. Please feel free to modify it to show me the solution. Thank you in advance.
public class Vehicle : PropertyChangedBase
{
public String Manufacturer { get; set; }
public String Model { get; set; }
public String Type { get; set; }
}
ShellViewModel
public class ShellViewModel : Conductor<Screen>, IHaveActiveItem
{
public ChildViewModel ChildVm { get; private set; }
public ObservableCollection<Vehicle> Vehicles { get; set; }
public ShellViewModel()
{
DisplayName = "Shell Window";
ChildVm = new ChildViewModel(this);
Vehicles = new ObservableCollection<Vehicle>();
SetData();
}
public void DisplayChild()
{
ActivateItem(ChildVm);
}
private void SetData()
{ // fill collection with some sample data
vh = new Vehicle();
vh.Manufacturer = "Chevrolet";
vh.Model = "Spark";
vh.Type = "LS";
Vehicles.Add(vh);
}
}
ShellView
<UserControl x:Class="CMWpfConductorParentChild.Views.ShellView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
d:DesignHeight="300"
d:DesignWidth="300"
mc:Ignorable="d">
<Grid Width="300" Height="300" HorizontalAlignment="Center"
ShowGridLines="True">
<Grid.RowDefinitions>
<RowDefinition Height="2*" />
<RowDefinition Height="10*" />
</Grid.RowDefinitions>
<Button x:Name="DisplayChild"
Grid.Row="0" Width="120" Height="40"
HorizontalContentAlignment="Center"
Content="Display Child View" />
<ContentControl x:Name="ActiveItem" Grid.Row="1" />
</Grid>
</UserControl>
ChildViewModel
public class ChildViewModel : Screen
{
public ShellViewModel ParentVm { get; private set; }
public ChildViewModel(ShellViewModel parent)
{
ParentVm = parent;
}
}
ChildView (the binding of DisplayMemberPath below doesn't work)
<UserControl x:Class="CMWpfConductorParentChild.Views.ChildView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
d:DesignHeight="300"
d:DesignWidth="300"
mc:Ignorable="d">
<Grid Width="300" Height="300">
<ListBox DisplayMemberPath="Manufacturer" ItemsSource="ParentVm.Vehicles" />
</Grid>
</UserControl>