Programmatically create Hyperlink Column in Silverlight DataGrid
I need to create a data grid which has various columns. One of the columns needs to be a hyperlink to a URL. For example I may have records of people in the grid and there name will link to a URL ging to the users file. Is 开发者_开发技巧this done in silverlight using a programmatically created hyperlink.
I did this in asp by doing a RowDataBind method, I need to do this in Silverlight:
protected void gvOrderData_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// Setup links
string OrderLink = "'http://crm1:5555/sfa/salesorder/edit.aspx?id={";
e.Row.Cells[0].Attributes.Add("onclick", "window.open(" + OrderLink + DataBinder.Eval(e.Row.DataItem, "SalesOrderID").ToString() + "}','tester','scrollbars=yes,resizable=yes');");
e.Row.Cells[0].Attributes.Add("onmouseover", "this.style.cursor='pointer'");
}
}
Why do you need to do it in code? It could be done in XAML using a DataGridTemplateColumn with an appropriate template e.g:
<sdk:DataGridTemplateColumn Header="View" CellTemplate="{StaticResource MyDataTemplate}">
</sdk:DataGridTemplateColumn>
..and define the template in the page resources
<DataTemplate x:Key="MyDataTemplate">
<HyperlinkButton x:Name="ViewLink"
Style="{StaticResource ViewButton}"
Click="ViewLink_Click">
</HyperlinkButton>
</DataTemplate>
You could add some logic to open a child window in the code behind, or following a purist MVVM path, add a command to handle the Hyperlink click event.
Unfortunately you can't create a DataTemplate in code... But you can create a DataTemplate in XAML as a resource, and assign it to a column in code:
((DataGridTemplateColumn)dg.Columns[0]).CellTemplate = (DataTemplate)this.Resources["dt"];
from: http://forums.silverlight.net/forums/p/12912/41962.aspx
精彩评论