我想在运行时向数据网格文本添加可点击/超链接文本。
这是我的DataGrid的XAML代码
<DataGrid Height="298" HorizontalAlignment="Left" Margin="18,273,0,0" Name="ResultDataGrid" VerticalAlignment="Top" Width="415"
RowBackground="#6B8DBBD1" AlternatingRowBackground="#CAD3D3BB" HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto"
CanUserSortColumns="True" IsReadOnly="True" HeadersVisibility="Column" HorizontalGridLinesBrush="#97000000" VerticalGridLinesBrush="#97000000" />
点击按钮,我将ItemSource添加到DataGrid
var resultDT = CDataBaseHelper.GetProjectsReviewedBtw(sDate, eDate);
if(resultDT !=null)
{
ResultDataGrid.AutoGenerateColumns = true;
ResultDataGrid.ItemsSource = LoadCollectionData(resultDT);
ResultDataGrid.Focus();
NoofRecordFoundLable.Content = resultDT.Rows.Count + " records found";
}
这是我的LoadCollectionData,它将返回集合
private List<ReviewedData> LoadCollectionData(DataTable resultData)
{
List<ReviewedData> result = new List<ReviewedData>();
if (resultData != null && resultData.Rows.Count > 0)
{
for (var i = 0; i < resultData.Rows.Count; ++i)
{
result.Add( new ReviewedData()
{
PROJECTNAME = resultData.Rows[i]["Name"].ToString(),
STATUS = resultData.Rows[i]["status"].ToString()
});
}
}
return result;
}
如何向每个PROJECTNAME添加可点击/超链接文本,以便我可以打开新窗口以显示DataGrid中显示的每个项目的更多项目详细信息?
任何建议。
此致
答案 0 :(得分:0)
您应该更多地依赖数据绑定和模板,而不是在运行时修改UI。这就是WPF的本质。
对于这种情况,您可能需要考虑使用DataGridHyperlinkColumn
。不要忘记关闭AutoGenerateColumns
功能,因为您要控制列的外观:
<DataGrid AutoGenerateColumns="False"
.... >
<DataGrid.Columns>
<DataGridHyperlinkColumn Binding="{Binding PROJECTNAME}" Header="Name">
<DataGridHyperlinkColumn.ElementStyle>
<Style>
<EventSetter Event="Hyperlink.Click" Handler="Hyperlink_Click"/>
</Style>
</DataGridHyperlinkColumn.ElementStyle>
</DataGridHyperlinkColumn>
<DataGridTextColumn Binding="{Binding STATUS}" Header="Status"/>
</DataGrid.Columns>
</DataGrid>
然后您可以根据需要处理超链接点击事件:
private void Hyperlink_Click(object sender, RoutedEventArgs e)
{
Hyperlink link = (Hyperlink)e.OriginalSource;
//Do something useful instead of just showing the hyperlink text in message box :
MessageBox.Show(link.NavigateUri.ToString());
}