我有一个模板,其中包含另一个模板,其中包含以下代码:
<DataGridHyperlinkColumn Header="Website" Binding="{Binding Website}"
IsReadOnly="True" SortMemberPath="Input.OriginalUri.AbsoluteUri" >
<DataGridHyperlinkColumn.ElementStyle>
<Style TargetType="TextBlock">
<EventSetter Event="Hyperlink.Click" Handler="OnHyperlinkClick" />
<Setter Property="Tag" Value="{Binding Website}"/>
</Style>
</DataGridHyperlinkColumn.ElementStyle>
</DataGridHyperlinkColumn>
但是因为它在模板中,所以当我运行代码时,我遇到了异常。
处理它的常用方法是使用命令,例如
<Hyperlink CommandParameter="{Binding Website.Uri.AbsoluteUri}" Command="{Binding Navigate, ElementName=UserControl}">
<TextBlock Text= "{Binding Website.Uri.AbsoluteUri}" />
</Hyperlink>
我试过了:
<DataGridHyperlinkColumn Header="Website" Binding="{Binding Website}"
IsReadOnly="True" SortMemberPath="Input.OriginalUri.AbsoluteUri" >
<DataGridHyperlinkColumn.ElementStyle>
<Style TargetType="TextBlock">
<Setter Property="Hyperlink.Command" Value="{Binding Navigate, ElementName=userControl}"/>
<Setter Property="Hyperlink.CommandParameter" Value="{Binding Website}"/>
</Style>
</DataGridHyperlinkColumn.ElementStyle>
</DataGridHyperlinkColumn>
但我收到以下错误:
Cannot find source for binding with reference 'ElementName=userControl'.
BindingExpression:Path=Navigate; DataItem=null; target element is 'TextBlock'
(Name=''); target property is 'Command' (type 'ICommand')
UserControl 声明如下:
<UserControl x:Name="userControl" ....
如何自定义DataGridHyperlinkColumn.ElementStyle
而不是设置事件处理程序,而是设置命令?
更新
命令代码如下所示:
public class NavigateCommand : ICommand
{
#region ICommand Members
public bool CanExecute(object parameter)
{
return true;
}
public event EventHandler CanExecuteChanged;
public void Execute(object parameter)
{
Process.Start(parameter.ToString());
}
#endregion
}