如何单击列表框中IsHitTestVisible为false的按钮?

时间:2014-04-02 10:08:01

标签: c# xaml button listbox

在列表框中,我有一个IsHitTestVisible为false的标题项。此项目包含一个应该可点击的按钮。但由于IsHitTestVisible,它现在不起作用。 如何只启用按钮?

请检查图片here

1 个答案:

答案 0 :(得分:-1)

在使用这个xaml代码之前检查你的列表框标题textblck是不是来自按钮。你的文本块可能来自按钮,这就是为什么按钮不起作用。通过设置宽度到textblock,你可以解决这个问题。以下代码适用于我

<Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">       
<Grid>
<ListBox Height="300" Width="300" Background="White" BorderThickness="0" BorderBrush="Transparent">       
    <ListBox.Style>
        <Style TargetType="ListBox">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="ListBox">
                        <Grid Background="White">
                            <Grid.RowDefinitions>
                                <RowDefinition Height="35"></RowDefinition>
                                <RowDefinition></RowDefinition>
                            </Grid.RowDefinitions>
                            <TextBlock Grid.Row="0" Text="Listbox header" FontSize="17" Foreground="Black" VerticalAlignment="Center" FontFamily="Segoe Ui Dark" HorizontalAlignment="Left" />
                            <Button Content="ok"  Grid.Row="0" HorizontalAlignment="Right" Width="100">
                                    <Button.Style>
                                        <Style TargetType="Button">                                                
                                                <EventSetter Event="Click" Handler="b1SetColor"/>                                              
                                        </Style>
                                    </Button.Style>
                                </Button>
                            <Border Grid.Row="1" SnapsToDevicePixels="True"  Background="Transparent" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}">
                                <ScrollViewer  x:Name="ScrollViewer" Padding="{TemplateBinding Padding}" Background="{TemplateBinding Background}" BorderBrush="Transparent" BorderThickness="0">
                                    <ItemsPresenter/>
                                </ScrollViewer>
                            </Border>
                        </Grid>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </ListBox.Style>
    <ListBoxItem>ListBoxItem1</ListBoxItem>
    <ListBoxItem>ListBoxItem2</ListBoxItem>

</ListBox>
</Grid>

    void b1SetColor(object sender, RoutedEventArgs e)
    {
        Button b = e.Source as Button;
        b.Background = new SolidColorBrush(Colors.Red);
    }

输出:按下按钮后会变成红色

enter image description here