带点击事件的WPF图像控制

Jes*_*lam 35 wpf xaml

我希望<Image>在我的WPF应用程序中使用一个响应鼠标点击的响应.只有'Mouse Up'和'Moue Down'活动才能开箱即用.我觉得这很特别.有没有办法扩展控件或使用另一个控件来产生相同的效果?

C8H*_*4O2 67

为了扩展Shawn Mclean的答案,WPF的一个强大功能是能够在完全改变控件外观的同时利用控件的行为.如果要创建一个行为就像按钮一样的图像(包括单击事件,命令绑定,默认按钮分配等),您可以将图像放在按钮控件中并重新设置该按钮以删除按钮"chrome".这将为您提供一个具有您想要的外观的按钮的漂亮API.您可以重用此样式,如果您有命令绑定到新图像按钮,此方法将减少在代码后面创建事件处理程序的需要.

创建这样的风格非常简单.只需在资源中创建一个带有命名键的新样式资源,并将此资源分配给按钮的Style属性.这是我扔在一起的一个例子:

<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="ButtonStyleTestApp.MainWindow"
x:Name="Window"
Title="MainWindow"
Width="640" Height="480">

<Window.Resources>
    <Style x:Key="NoChromeButton" TargetType="{x:Type Button}">
        <Setter Property="Background" Value="Transparent"/>
        <Setter Property="BorderThickness" Value="1"/>
        <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}"/>
        <Setter Property="HorizontalContentAlignment" Value="Center"/>
        <Setter Property="VerticalContentAlignment" Value="Center"/>
        <Setter Property="Padding" Value="1"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type Button}">
                    <Grid x:Name="Chrome" Background="{TemplateBinding Background}" SnapsToDevicePixels="true">
                        <ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
                    </Grid>
                    <ControlTemplate.Triggers>                          
                        <Trigger Property="IsEnabled" Value="false">
                            <Setter Property="Foreground" Value="#ADADAD"/>
                            <Setter Property="Opacity" TargetName="Chrome" Value="0.5"/>
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</Window.Resources>

<Grid x:Name="LayoutRoot" Background="#FF44494D">
    <Button Style="{DynamicResource NoChromeButton}" Click="ButtonClicked" >
        <Image Source="Desert.png" Stretch="None"/>
    </Button>
</Grid>
</Window>
Run Code Online (Sandbox Code Playgroud)


Sha*_*ean 29

使用MouseUp.无论如何都无法对Tab控件进行制表或聚焦,因此这是单击它的唯一方法.

另一种选择是将图像放在一个按钮中,并通过编辑控件模板删除所有样式,使其看起来像一个图像.这样,您可以使用键盘专注于它.

  • 调焦="真" (6认同)
  • 不要使用MouseUp事件而不是Click事件 - 这样您的应用程序可能无法使用禁用的辅助功能工具. (4认同)