我正在制作一个WPF应用程序,在其中我有一个图像控件,我想从我的视图模型绑定一个自定义命令对象到该控件,当单击图像时,该命令将执行。我已经从我的视图模型公开了命令对象,只需要将其绑定到图像控件即可。
是否可能将此命令对象绑定到图像控件?如果可以,任何建议都将不胜感激。
是否可能将此命令对象绑定到图像控件?如果可以,任何建议都将不胜感激。
以下是我个人最喜欢的解决方案,如果我想在不将其包含在另一个控件中的情况下使用命令获取图像。
<Image Source="Images/tick.png" Cursor="Hand" Tooltip="Applies filter">
<Image.InputBindings>
<MouseBinding Gesture="LeftClick" Command="{Binding ApplyFilter, Mode=OneTime}" />
</Image.InputBindings>
</Image>
我设置了它的属性Hand
和Tooltip
,以便更清楚地表明它是一个操作而不是静态图像。
您需要将图像放在按钮中,并将按钮绑定到命令:
<Button Command="{Binding MyCommand}">
<Image Source="myImage.png" />
</Button>
如果您不想要标准按钮样式,只需更改按钮的模板,类似于以下内容:
<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>
请注意,您还需要更改其他属性以覆盖默认的按钮样式,否则上面的模板将使用默认的按钮背景和边框:<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>
使用超链接Hyperlink
代替按钮可能更简单:
<TextBlock DockPanel.Dock="Top">
<Hyperlink Command="{Binding SomeCommand}">
<Image Source="image.png" />
</Hyperlink>
</TextBlock>
<Style x:Key={x:Type Hyperlink}" TargetType="Hyperlink">
<Setter Property="TextDecorations"
Value="{x:Null}" />
</Style>
@Robert Rossney的回答简化版:
<TextBlock>
<Hyperlink Command="{Binding SomeCommand}" TextDecorations="{x:Null}">
<Image Source="{StaticResource image.png}" Width="16" />
</Hyperlink>
</TextBlock>
插入图片的最佳方式是使用{StaticResource x}
,请参见WPF图像资源。
重置按钮的控件模板并在控件模板中使用图像。
<Button Width="100" Height="100" Command="{Binding SampleCommand}">
<Button.Template>
<ControlTemplate TargetType="{x:Type Button}">
<Image Stretch="Uniform" Source="Images/tick.png"></Image>
</ControlTemplate>
</Button.Template>
</Button>