在带有标题的ComboBox中使用多个列时,SelectedIndex始终保持为-1

时间:2014-07-19 21:07:53

标签: c# wpf combobox selectedindex

我有一个带标题的多列ComboBox。我可以使用this回答来解决这个问题。

以下是我使用过的XAML:

<CollectionViewSource x:Key="GroupNamesWithCorrespondingEffectsCollection" Source="{Binding GroupNamesWithCorrespondingEffects}" />

<CompositeCollection x:Key="Items">
    <ComboBoxItem IsEnabled="False" Background="#FF2A2A2A" Foreground="White">
        <Grid TextElement.FontWeight="Bold" >
            <Grid.ColumnDefinitions>
                <ColumnDefinition SharedSizeGroup="A" />
                <ColumnDefinition Width="50" />
                <ColumnDefinition SharedSizeGroup="B" />
            </Grid.ColumnDefinitions>
            <Grid.Children>
                <TextBlock Grid.Column="0" Text="Group Name" />
                <TextBlock Grid.Column="2" Text="Effect" />
            </Grid.Children>
        </Grid>
    </ComboBoxItem>
    <CollectionContainer Collection="{Binding Source={StaticResource GroupNamesWithCorrespondingEffectsCollection}}" />
</CompositeCollection>

<DataTemplate DataType="{x:Type helpers:GroupNameWithCorrespondingEffect}">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition SharedSizeGroup="A" />
            <ColumnDefinition Width="50" />
            <ColumnDefinition SharedSizeGroup="B" />
        </Grid.ColumnDefinitions>
        <Grid.Children>
            <TextBlock Grid.Column="0" Text="{Binding GroupName}" />
            <TextBlock Grid.Column="2" Text="{Binding CorrespondingEffect}" />
        </Grid.Children>
    </Grid>
</DataTemplate>

<ComboBox ItemsSource="{DynamicResource Items}" 
          SelectedValue="{Binding GroupNameWithCorrespondingEffect}"
          SelectedValuePath="GroupID"
          DisplayMemberPath="GroupName" />

注意:

C#代码未发布,因为我认为没有必要在此处发布。如果有人想看看C#代码,请告诉我&amp;我会发布它。

问题:

我想在CodeBehind文件中检查ComboBox的SelectedIndex。但我注意到SelectedIndex始终保持-1。可能是什么问题?我应该如何克服它?

1 个答案:

答案 0 :(得分:1)

您已将 SelectedValue 绑定到 GroupNameWithCorrespondingEffect ,我怀疑其类型为GroupNameWithCorrespondingEffect且同时绑定了 {{1} SelectedValuePath ,可以是int或uint。

SelectedValue和SelectedValuePath应始终属于同一类型。在您的情况下,您可以删除SelectedValuePath并直接绑定SelectedValue。

GroupID