【发布时间】:2018-07-03 22:56:42
【问题描述】:
我正在将一个 WPF 应用程序放在一起,其中我有一个图像控件,我想将一个自定义命令对象绑定到我的视图模型中,该对象将在单击图像时执行。我已经从我的视图模型中公开了命令对象,只需要将它绑定到图像控件。
是否可以将此命令对象绑定到图像控件?如果是这样,任何建议将不胜感激。
【问题讨论】:
标签: wpf
我正在将一个 WPF 应用程序放在一起,其中我有一个图像控件,我想将一个自定义命令对象绑定到我的视图模型中,该对象将在单击图像时执行。我已经从我的视图模型中公开了命令对象,只需要将它绑定到图像控件。
是否可以将此命令对象绑定到图像控件?如果是这样,任何建议将不胜感激。
【问题讨论】:
标签: 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 image resources
【讨论】:
重置按钮的控件模板并在控件模板中使用图像..
<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>
【讨论】: