我使用代码创建一个列表视图,我希望第二列包含一个超链接,打开默认浏览器并加载网址。
我创建了类似的列表视图:
GridView myGridView = new GridView();
myGridView.AllowsColumnReorder = false;
ListView l1 = new ListView();
GridViewColumn gvc0 = new GridViewColumn();
gvc0.DisplayMemberBinding = new Binding("AA");
gvc0.Header = "A/A";
gvc0.Width = 30;
myGridView.Columns.Add(gvc0);
GridViewColumn gvc1 = new GridViewColumn();
gvc1.DisplayMemberBinding = new Binding("Description");
gvc1.Header = "Description";
gvc1.Width = 300;
myGridView.Columns.Add(gvc1);
l1.View = myGridView;
我也像这样填写列表视图:
l1.Items.Add(new { AA = aa++, Description = descriptions});
我希望描述文本是一个超链接。它可以吗?
答案 0 :(得分:1)
在代码隐藏中,您可以创建CellTemplate
:
GridView myGridView = new GridView();
myGridView.AllowsColumnReorder = false;
ListView l1 = new ListView();
GridViewColumn gvc0 = new GridViewColumn();
gvc0.DisplayMemberBinding = new Binding("AA");
gvc0.Header = "A/A";
gvc0.Width = 30;
myGridView.Columns.Add(gvc0);
GridViewColumn gvc1 = new GridViewColumn();
gvc1.Header = "Description";
gvc1.Width = 300;
FrameworkElementFactory fef = new FrameworkElementFactory(typeof(TextBlock));
FrameworkElementFactory hyperlinkHolder = new FrameworkElementFactory(typeof(Hyperlink));
hyperlinkHolder.SetBinding(Hyperlink.NavigateUriProperty, new Binding("Description"));
hyperlinkHolder.AddHandler(Hyperlink.RequestNavigateEvent, new RequestNavigateEventHandler(Hyperlink_RequestNavigate));
FrameworkElementFactory fef2 = new FrameworkElementFactory(typeof(TextBlock));
Binding placeBinding = new Binding();
fef2.SetBinding(TextBlock.TextProperty, placeBinding);
placeBinding.Path = new PropertyPath("Description");
hyperlinkHolder.AppendChild(fef2);
fef.AppendChild(hyperlinkHolder);
var dataTemplate = new DataTemplate();
dataTemplate.VisualTree = fef;
dataTemplate.DataType = typeof(ListViewItem);
gvc1.CellTemplate = dataTemplate;
myGridView.Columns.Add(gvc1);
l1.View = myGridView;
事件处理程序:
private void Hyperlink_RequestNavigate(object sender, RequestNavigateEventArgs e)
{
Process.Start(new ProcessStartInfo(e.Uri.AbsoluteUri));
e.Handled = true;
}
你应该使用XAML来做到这一点,它比你在代码隐藏中定义的所有GUI的第一个解决方案更清晰。
<ListView Name="l1">
<ListView.View>
<GridView>
<GridView.Columns>
<GridViewColumn Header="A/A" Width="30" DisplayMemberBinding="{Binding AA}" />
<GridViewColumn Header="Description" Width="300">
<GridViewColumn.CellTemplate>
<DataTemplate>
<TextBlock>
<Hyperlink NavigateUri="{Binding Description}" RequestNavigate="Hyperlink_RequestNavigate">
<TextBlock Text="{Binding Description}" />
</Hyperlink>
</TextBlock>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
</GridView.Columns>
</GridView>
</ListView.View>
</ListView>