1

我有一个模板,其中包含另一个模板,其中包含以下代码:

<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
    }
4

1 回答 1

2

不是您问题的真正答案,但也许是一种解决方法:将您的 Column 变成模板列并在其中显示一个样式按钮,类似于:

<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>
于 2012-06-23T21:29:12.750 回答