我有一个包含其他模板的模板,其中包含以下代码:
<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
}
答案 0 :(得分:2)
不是你的问题的答案,但也许是一种解决方法:将你的专栏变成模板栏并在其中显示一个样式的按钮,其中包括:
<DataGridTemplateColumn Header="Website"
IsReadOnly="True" SortMemberPath="Input.OriginalUri.AbsoluteUri" >
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button Content="{Binding Website}" Command="{StaticResource NavigateCommand}" CommandParameter="{Binding Website}" Style={StaticResource LinkStyle}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>