WPF列表框绑定:SelectedItem未设置

Gar*_*thD 3 c# data-binding wpf listbox mvvm

我将ListBox简化为以下XAML

<ListBox ItemsSource="{Binding Properties}" 
     DisplayMemberPath="Name" 
     SelectedItem="SelectedProperty" />
Run Code Online (Sandbox Code Playgroud)

在我的ViewModel中:

private List<Property> propertyList;
private Property selectedProperty;
public List<Property> Properties 
{ 
    get 
    { 
        return propertyList; 
    } 
    set 
    { 
        propertyList = value;
        NotifyPropertyChanged("Properties");
    } 
}
public Property SelectedProperty
{
    get
    {
        return selectedProperty;
    }
    set
    {
        NotifyPropertyChanged("SelectedProperty");
        selectedProperty= value;
    }
}
Run Code Online (Sandbox Code Playgroud)

我的列表框填充正常,但无论我尝试什么,当我在列表框中选择一个项目时,我似乎无法更新SelectedProperty.我已经尝试将其全部切换为使用ObservableCollection而不是List为CollectionChanged添加事件处理程序,但这没有用.

我确信我错过了一些愚蠢的东西,并且看不到树木的木头.我到达了我的系绳的末端,需要有人介入并提供帮助.

dev*_*tal 9

你需要绑定到SelectedProperty:

<ListBox ItemsSource="{Binding Properties}" 
 DisplayMemberPath="Name" 
 SelectedItem="{Binding SelectedProperty}"  />
Run Code Online (Sandbox Code Playgroud)

  • 添加模式= TwoWay. (4认同)