So I've got a hyperlink that I have hooked up to the code behind like so:
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. 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.
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.
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. as I said if you are doing MVVM this should be obvious:
<Button Style="{StaticResource HyperLinkButton}"
Content="Some Link"
Command={Binding Path=MyCommand, Mode=OneWay/>