如何使用wpf数据网格从DataGridHyperlinkColumn中获取选定值

时间:2014-08-12 05:30:12

标签: c# wpf datagrid

我的数据网格有一个DataGridHyperlinkColumn,但是点击那个超链接我没有得到这个值。我的数据网格是,

<datagrid name="datagrid1">
   <column>
      <DataGridHyperlinkColumn Binding="{Binding ID}" Header="ID"  Width="100" >
         <DataGridHyperlinkColumn.ElementStyle>
            <Style TargetType="TextBlock" >
               <EventSetter  Event="Hyperlink.Click" Handler="Hyperlink_Click"  />
            </Style>
         </DataGridHyperlinkColumn.ElementStyle>
      </DataGridHyperlinkColumn>
   </column>
</datagrid>

我将如何在Hyperlink_Click方法中获取Id。?

2 个答案:

答案 0 :(得分:5)

您可以从ID的{​​{1}} TextBlock获取DataContext

private void Hyperlink_Click(object sender, RoutedEventArgs e)
{
    //cast sender to TextBlock, and get it's data context
    var dc = ((TextBlock)sender).DataContext;
    //cast data context to your model type, and get the ID property
    var id = ((YourModelType)dc).ID;
}

或者您可以设置其他答案中建议的Tag TextBlock属性:

<DataGridHyperlinkColumn Binding="{Binding ID}" Header="ID"  Width="100" >
    <DataGridHyperlinkColumn.ElementStyle>
        <Style TargetType="TextBlock" >
            <Setter Property="Tag" Value="{Binding ID}" />
            <EventSetter  Event="Hyperlink.Click" Handler="Hyperlink_Click"  />
        </Style>
    </DataGridHyperlinkColumn.ElementStyle>
</DataGridHyperlinkColumn>

然后你可以在事件处理程序中获得ID值,如下所示:

private void Hyperlink_Click(object sender, RoutedEventArgs e)
{
    TextBlock textblock = (TextBlock)sender;
    string id = (string)textblock.Tag;
}

答案 1 :(得分:0)

您可以使用ID设置超链接的Tag属性,并获取此标记值

 private void  Hyperlink_Click(object sender, RoutedEventArgs e)
        {
            HyperlinkButton hlb = (HyperlinkButton)sender;
            if(hlb !=null){
               var id = hlb.tag
            }

        }