Binding SelectedItem of Combobox in wpf

时间:2018-12-03 12:57:39

标签: c# wpf combobox binding

I've looked through a lot of articles about this subject but so far none have suggested a solution that works for me.

I'm working with a FilteredComboBox that I've found in another article on this site (Dynamic filter of WPF combobox based on text input, the fixed version by YantingChen). I'm trying to get it to work with my code.

I have a viewmodel that performs the following code when the view is opened:

Object = _context.ObjectReader.GetObjectById(i); //returns an object with property Prop, that is of type Item
Items = _context.ItemReader.GetAllItems(); //returns an ObservableCollection<Item>. Item has a property Name
RaisePropertyChanged(nameof(Object));
RaisePropertyChanged(nameof(Items));

My xaml uses this for the FilteredComboBox:

<local:FilteredComboBox ItemsSource="{Binding Items}"
                        SelectedItem="{Binding Object.Prop}"
                        DisplayMemberPath="Name"
                        Width="200">
    <local:FilteredComboBox.ItemsPanel>
        <ItemsPanelTemplate>
            <VirtualizingStackPanel VirtualizationMode="Recycling"/>
        </ItemsPanelTemplate>
    </local:FilteredComboBox.ItemsPanel>
</local:FilteredComboBox>

What I'm trying to accomplish with this is that the combobox shows the current value of Object.Prop when the view is opened, but this does not happen with the current setup. From what I've gathered by googling around for this problem, binding to the SelectedItem of a combobox comes with some odd difficulties, but I'm hoping someone here will be able to point me in the right direction.

I've tried the following:

<local:FilteredComboBox ItemsSource="{Binding Items}"
                        SelectedItem="{Binding Object.Prop}"
                        SelectedValue="{Binding Object.Prop.Name}"
                        DisplayMemberPath="Name"
                        Width="200">
    <local:FilteredComboBox.ItemsPanel>
        <ItemsPanelTemplate>
            <VirtualizingStackPanel VirtualizationMode="Recycling"/>
        </ItemsPanelTemplate>
    </local:FilteredComboBox.ItemsPanel>
</local:FilteredComboBox>

This almost seemed to work except it's somehow setting the selection to the wrong item in the itemssource.

0 个答案:

没有答案