WPF 图像命令绑定 [英] WPF Image Command Binding

查看:19
本文介绍了WPF 图像命令绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将一个 WPF 应用程序放在一起,其中我有一个图像控件,我想将自定义命令对象绑定到我的视图模型中,该对象将在单击图像时执行.我已经从我的视图模型中暴露了命令对象,只需要将它绑定到图像控件.

I'm putting a WPF application together in which I have an image control which I want to bind a custom command object to from my view model that will execute when the image is clicked. I have exposed the command object from my view model and just need to bind it to the image control.

是否可以将此命令对象绑定到图像控件?如果是这样,任何建议将不胜感激.

Is it possible to bind this command object to an image control? If so any advice would be appreciated.

推荐答案

需要将图片放入按钮中,并将按钮绑定到命令:

You need to put the image in a button, and bind the button to the command:

<Button Command="{Binding MyCommand}">
    <Image Source="myImage.png" />
</Button>

如果您不想要标准按钮镶边,只需使用以下内容更改按钮模板:

If you don't want the standard button chrome, just change the template of the button with something like that:

<ControlTemplate x:Key="tplFlatButton" TargetType="{x:Type Button}">
    <Border Width="{TemplateBinding Width}"
            Height="{TemplateBinding Height}"
            Background="{TemplateBinding Background}"
            BorderBrush="{TemplateBinding BorderBrush}"
            BorderThickness="{TemplateBinding BorderThickness}">
        <ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
                          VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
                          TextElement.Foreground="{TemplateBinding Foreground}"
                          TextElement.FontFamily="{TemplateBinding FontFamily}"
                          TextElement.FontSize="{TemplateBinding FontSize}"
                          TextElement.FontStretch="{TemplateBinding FontStretch}"
                          TextElement.FontWeight="{TemplateBinding FontWeight}"/>
    </Border>
</ControlTemplate>

注意,你还需要更改其他属性来覆盖默认按钮样式,否则上面的模板将使用默认按钮背景和边框:

Note that you will also need to change other properties to override the default button style, otherwise the template above will use the default button background and border:

<Style x:Key="stlFlatButton" TargetType="{x:Type Button}">
    <Setter Property="Background" Value="{x:Null}" />
    <Setter Property="BorderBrush" Value="{x:Null}" />
    <Setter Property="BorderThickness" Value="0" />
    <Setter Property="Template" Value="{StaticResource tplFlatButton}" />
</Style>

这篇关于WPF 图像命令绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆