[英]Is it possible to set e.Handled = true in a RelayCommand?
So I've got a hyperlink that I have hooked up to the code behind like so: 因此,我有一个超链接,已将其链接到后面的代码,如下所示:
Xaml Xaml
<TextBlock x:Name="Hyperlink" HorizontalAlignment="Left" VerticalAlignment="Bottom" Margin="3" FontSize="14" Foreground="White">
<Hyperlink NavigateUri="{Binding StreetViewString}" RequestNavigate="Hyperlink_RequestNavigate" Foreground="White" StylusDown="Hyperlink_StylusDown" TouchDown="Hyperlink_TouchDown">
Google
</Hyperlink>
</TextBlock>
Code Behind 背后的代码
private void addToDiary_MouseDown(object sender, MouseButtonEventArgs e)
{
((sender as Button).DataContext as MyViewModel).MyCommand.Execute(null);
e.Handled = true;
}
But I would like to hook this straight up to the command it is executing 但是我想直接将其与正在执行的命令联系起来
private ICommand _myCommand;
public ICommand MyCommand
{
get
{
return _myCommand
?? (_myCommand= CommandFactory.CreateCommand(
() =>
{
DoSomething();
}));
}
}
but the only thing that is stopping me is that I cannot set e.Handled = true
from my command. 但是唯一让我停下的是,我无法从命令中设置
e.Handled = true
。 Is it possible to do this without using the code behind? 是否可以不使用后面的代码来执行此操作?
I am going to presume you're using MVVM and ideally you want to be able to 'handle' the click of the hyperlink in the ViewModel and not in the View - which is the correct way to do this. 我假设您使用的是MVVM,理想情况下,您希望能够“处理” ViewModel中而不是View中的超链接单击-这是正确的方法。
In which you are probably best using a normal WPF button which has been styled to look like a hyperlink and then bind in the Command property of the button to an instance of your ICommand implmentation. 在其中最好使用普通的WPF按钮,该按钮的样式看起来像超链接,然后将按钮的Command属性绑定到ICommand实现的实例。
The following should style the button: 以下应该为按钮设置样式:
<Style x:Key="HyperLinkButton"
TargetType="Button">
<Setter
Property="Template">
<Setter.Value>
<ControlTemplate
TargetType="Button">
<TextBlock
TextDecorations="Underline">
<ContentPresenter /></TextBlock>
</ControlTemplate>
</Setter.Value>
</Setter>
<Setter
Property="Foreground"
Value="Blue" />
<Style.Triggers>
<Trigger
Property="IsMouseOver"
Value="true">
<Setter
Property="Foreground"
Value="Red" />
</Trigger>
</Style.Triggers>
</Style>
Applying the Style and binding the Command property, this requires you have bound the DataContext of the containing control\\view to the ViewModel. 应用样式并绑定Command属性,这要求您已将包含控件\\ view的DataContext绑定到ViewModel。 as I said if you are doing MVVM this should be obvious:
如我所说,如果您正在执行MVVM,这应该很明显:
<Button Style="{StaticResource HyperLinkButton}"
Content="Some Link"
Command={Binding Path=MyCommand, Mode=OneWay/>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.