Выбор элемента в выпадающем списке в рамках MVVM - PullRequest
2 голосов
/ 30 июля 2011

У меня есть комбинированный список WPF, связанный с ObservableCollection ItemCategoryList

 <ComboBox Grid.Column="1" Grid.Row="2" Height="Auto" HorizontalAlignment="Stretch" Margin="0" Name="comboBox1" VerticalAlignment="Stretch" Width="Auto" ItemsSource="{Binding Path= ItemCategoryList}" DisplayMemberPath="Name" SelectedItem="{Binding Path=SelectedItemCategory,UpdateSourceTrigger=PropertyChanged}"  SelectedIndex="{Binding Path=SelectIndexItemCategory}" />

и DataGrid, привязанный к ObservableCollection ItemTypeList, а ItemType имеет вложенный объект ItemCategory типа ItemCategory

    <DataGrid AutoGenerateColumns="False" Grid.ColumnSpan="3" Grid.Row="3" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Width="Auto" Margin="10" 
              ItemsSource="{Binding ItemTypeList}"
              SelectedItem="{Binding SelectedItemType}" 
              CanUserDeleteRows="False" 
              CanUserAddRows="False">
        <DataGrid.Columns>
            <DataGridTextColumn Binding="{Binding Path=ItemTypeID}" Header="ItemTypeID" IsReadOnly="True" Visibility="Hidden" />
            <DataGridTextColumn Binding="{Binding Path=Name}" Header="Item Type Name" IsReadOnly="True" />
            <DataGridTextColumn Binding="{Binding Path=ItemCategory.Name}" Header="Item Category" IsReadOnly="True" />
        </DataGrid.Columns>
    </DataGrid>

Теперь, когда я выбираю строку в сетке данных, я хочу, чтобы в выпадающем списке был выбран соответствующий ItemCategory для этого ItemType

    private ItemType selectedItemType;

    public ItemType SelectedItemType
    {
        get { return selectedItemType; }
        set { 
            selectedItemType = value;
            RaisePropertyChanged("SelectedItemType");
            if (selectedItemType != null)
            {
                ItemTypeName = selectedItemType.Name;
                SelectIndexItemCategory = ItemCategoryList.IndexOf(SelectedItemCategory);
            }


        }
    }

    private int selectIndexItemCategory;

    public int SelectIndexItemCategory
    {
        get { return selectIndexItemCategory; }
        set { selectIndexItemCategory = value;
        RaisePropertyChanged("SelectIndexItemCategory");
        }
    }

Edit:

Проблема, кажется, здесь:

SelectIndexItemCategory = ItemCategoryList.IndexOf(SelectedItemCategory);

Нет ли в коллекции метода поиска, подобного списку, который я могу использовать?

1 Ответ

2 голосов
/ 01 августа 2011

Использовать привязку к SelectedItem вместо SelectedIndex.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...