首页 > 解决方案 > WPF 将启用按钮移到前面

问题描述

我有一个包含许多矩形的画布,如下所示:

   <Canvas x:Name="canvas">
        <ItemsControl ItemsSource="{Binding Rectangles}" Canvas.ZIndex="5" Name="RectanglesControl">
            <ItemsControl.ItemsPanel>
                <ItemsPanelTemplate>
                    <Canvas />
                </ItemsPanelTemplate>
            </ItemsControl.ItemsPanel>
            <ItemsControl.ItemContainerStyle>
                <Style TargetType="ContentPresenter">
                    <Setter Property="Panel.ZIndex" Value="1" />
                </Style>
            </ItemsControl.ItemContainerStyle>
            <ItemsControl.Resources>
                <DataTemplate DataType="{x:Type Rectangle}">
                    <Button Command="{Binding Command}"
                            IsEnabled="{Binding IsEnabled}">
                        <Button.Template>
                           <ControlTemplate TargetType="{x:Type Button}">
                                <Path Data="{Binding Geometry}"
                                     Fill="{Binding FillBrush}"
                                     IsHitTestVisible="True"
                                     Cursor="Hand" 
                                     Opacity="{Binding IsFillVisible, Converter={StaticResource BoolToDoubleConverter}}"/>
                            </ControlTemplate>
                        </Button.Template>
                    </Button>
                </DataTemplate>
            </ItemsControl.Resources>
        </ItemsControl>
    </Canvas>

为每个矩形创建一个按钮,并使用按钮模板将这些按钮“伪装”为矩形。这是为了使矩形可点击。

现在的问题是某些按钮已启用,而有些则未启用。结果,如果未启用的按钮位于已启用的按钮之上,则无法单击已启用的按钮。

有没有办法将启用的按钮移到前面,或者允许通过未启用的按钮单击启用的按钮?

标签: c#wpf

解决方案


使用 DataTrigger 设置 ZIndex 属性:

<ItemsControl.ItemContainerStyle>
    <Style TargetType="ContentPresenter">
        <Style.Triggers>
            <DataTrigger Binding="{Binding IsEnabled}" Value="True">
                <Setter Property="Panel.ZIndex" Value="1"/>
            </DataTrigger>
        </Style.Triggers>
    </Style>
</ItemsControl.ItemContainerStyle>

推荐阅读