CheckBoxes的ComboBox在行单击

时间:2017-05-18 12:57:34

标签: wpf xaml checkbox combobox

我有一个复选框组合框,允许用户选择多个温度范围。当用户单击复选框或复选框旁边的文本时,会正确选中这些框,并且我的组合框文本会更新以添加/删除所选温度。但是,如果我在文本框右侧检查组合框的区域,则复选框不会切换,而是在组合框中输入命名空间文本。 ComboBox Text

这是我的XAML

<ComboBox x:Name="cbDegrees" ItemsSource="{Binding m_DegreeValues}" Text="Degrees" IsEditable="True" IsReadOnly="True" Grid.Row="0" Grid.Column="0" Margin="5" Background="Gray" >
                <ComboBox.ItemTemplate>
                    <DataTemplate>
                        <CheckBox Name="chkDegrees" Content="{Binding Name}" Checked="Degrees_CheckBox_Click" Unchecked="Degrees_CheckBox_Click"  IsChecked="{Binding Path=IsSelected, Mode=TwoWay}">
                        </CheckBox>
                    </DataTemplate>
                </ComboBox.ItemTemplate>
</ComboBox>

当我点击该项目中温度的任何位置时,我希望复选框切换。

2 个答案:

答案 0 :(得分:1)

您可以定义ItemContainerStyle水平CheckBox拉伸:

<ComboBox x:Name="cbDegrees" ItemsSource="{Binding m_DegreeValues}" Text="Degrees" IsEditable="True" IsReadOnly="True" Grid.Row="0" Grid.Column="0" Margin="5" Background="Gray" >
    <ComboBox.ItemContainerStyle>
        <Style TargetType="ComboBoxItem">
            <Setter Property="HorizontalContentAlignment" Value="Stretch" />
        </Style>
    </ComboBox.ItemContainerStyle>
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <CheckBox Name="chkDegrees" Content="{Binding Name}" Checked="Degrees_CheckBox_Click" Unchecked="Degrees_CheckBox_Click"  IsChecked="{Binding Path=IsSelected, Mode=TwoWay}">
            </CheckBox>
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>

答案 1 :(得分:1)

生成的默认ComboBoxItem未设置为拉伸并填充所有可用空间。如果你将ComboBox包裹在像DockPanel这样的背景属性集中,你可以看到这一点。

<ComboBox.ItemTemplate>
    <DataTemplate>
        <DockPanel Background="CornflowerBlue">
            <CheckBox Name="chkDegrees" Content="{Binding Name}" .. />
        </DockPanel>
    </DataTemplate>
</ComboBox.ItemTemplate>

要解决此问题,请设置ComboBoxItem样式,以便将HorizontalContentAlignment设置为Stretch

<ComboBox.Resources>
    <Style TargetType="{x:Type ComboBoxItem}">
        <Setter Property="HorizontalContentAlignment" Value="Stretch" />
    </Style>
</ComboBox.Resources>