0

My MainView has a ViewModel called MainViewModel. MainViewModel creates a dialog and I want the dialogs ViewModel to be the already existing MainViewModel

To create the dialog from the MainViewModel I do

var MyInnerDlg = new MyInnerDlgView();
MyInnerDlg.DataContext = this;
MyInnerDlg.ShowDialog();

In the dialog I have a ListBox which I bind to a collection from my MainViewModel

public ObservableCollection<MyItemViewModel> MyList { get; set; }

XAML of the dialog

<Border Margin="5" BorderThickness="2">
    <ListBox ItemsSource="{Binding MyList}" DisplayMemberPath="{Binding MyList.Name}" />
</Border>

The Name property is in MyItemViewModel. With the above code I get the error:

Name property not found in MainViewModel.

How can I refer to each of the items Name property?

default
  • 11,485
  • 9
  • 66
  • 102
user2837961
  • 1,505
  • 3
  • 27
  • 67

2 Answers2

2

DisplayMemberPath should probably not be a Binding. Change it to the property name of the property that you want to display, i.e. "Name"

<ListBox ItemsSource="{Binding MyList}" DisplayMemberPath="Name" />

Also, a general suggestion is not to have public setters on lists, since you can get unindented behavior. Instead, use a backing field and remove the setter.

Community
  • 1
  • 1
default
  • 11,485
  • 9
  • 66
  • 102
0

Try changing :

 <ListBox ItemsSource="{Binding MyList}" DisplayMemberPath="{Binding MyList.Name}">

To:

 <ListBox ItemsSource="{Binding MyList}" DisplayMemberPath="{Binding Name}">

Or try adding:

 <Page.Resources>
    <local:MyItemViewModel x:Key="DataContext" />   
 </Page.Resources> 

 <ListBox DataContext="{StaticResource DataContext}" ItemsSource="{Binding MyList}" DisplayMemberPath="{Binding MyList.Name}"> </ListBox>

Usually i add a ViewModel in the xaml file itself.

 <Page.Datacontext>
    <local:MyItemViewModel/>   
 </Page.Datacontext> 
Developer
  • 59
  • 7