从绑定的wpf超链接启动进程

时间:2011-07-20 22:04:35

标签: .net wpf data-binding

让WPF超链接在其(数据绑定)文本内容上运行Process.Start的简单方法是什么?

1 个答案:

答案 0 :(得分:0)

一种方法(可以通过重构到UserControl或静态类或ValueConverter或......来改进)是将超链接绑定到ViewModel上的命令并传入超链接的内容(我不能找到一种做相对绑定的方法)作为命令参数。

WPF代码段

<TextBlock>
    <TextBlock.DataContext>
        <ViewModels:ViewModel />
    </TextBlock.DataContext>
    <Hyperlink Command="{Binding LaunchHyperlinkCommand}" CommandParameter="{Binding ElementName=_content, Path=Text}">
    <Run Text="{Binding FilePath, Mode=OneWay}" Name="_content"/>
    </Hyperlink>
</TextBlock>

C#DataContext类代码段(注意:使用Prism

public class ViewModel : NotificationObject
{
    public string FilePath { get; private set; }

    public DelegateCommand<string> LaunchHyperlinkCommand { get; set; }

    public ViewModel()
    {
        LaunchHyperlinkCommand = new DelegateCommand<string>(LaunchHyperlink);
    }

    private static void LaunchHyperlink(string link)
    {
        try
        {
            Process.Start(link);
        }
        catch (Exception e)
        {
            MessageBox.Show(e.Message);
        }
    }
}