gpt4 book ai didi

wpf - 绑定(bind)到带有可点击链接的列表框

转载 作者:行者123 更新时间:2023-12-03 10:13:12 25 4
gpt4 key购买 nike

我正在开发我的第一个 WPF 应用程序,它非常棒。不过今天遇到了一些困难。

我的应用充当网络搜索器——访问搜索引擎并检索链接。我想以可点击的格式显示链接。我想我会将生成的 string[] 链接绑定(bind)到 ListBox 并在其中放置一个 Hyperlink。经过一番谷歌搜索后,这是我想出的:

<ListBox Height="200" ItemsSource="{Binding Path=UrlsFound, Mode=OneWay}" Name="listBox1" Width="727">
<ListBox.Resources>
<DataTemplate DataType="String">
<TextBlock>
<Hyperlink NavigateUri="{Binding}" RequestNavigate="Hyperlink_RequestNavigate">
<TextBlock Text="{Binding}" />
</Hyperlink>
</TextBlock>
</DataTemplate>
</ListBox.Resources>
</ListBox>

在代码隐藏中:

private void Hyperlink_RequestNavigate(object sender, RequestNavigateEventArgs e)
{
Process.Start(new ProcessStartInfo(e.Uri.AbsoluteUri));
e.Handled = true;
}

我在网络上的一些地方发现了 RequestNavigate 代码。

所以一切都很好地绑定(bind)并且列表框中包含所有链接,但它们不可点击。我在 RequestNavigate 上添加了一个断点,它没有被击中(也尝试双击),甚至还尝试添加一个 Click 处理程序。我做错了什么?

最佳答案

我认为问题在于您的 DataTemplate 与您的列表项没有任何关联。您应该指定 ListBox.ItemTemplate 而不是仅在资源部分定义 DataTemplate(它不像没有键的样式那样工作)。

<ListBox Height="200" ItemsSource="{Binding Path=UrlsFound, Mode=OneWay}" Name="listBox1" Width="727">
<ListBox.ItemTemplate>
<DataTemplate DataType="String">
<TextBlock>
<Hyperlink NavigateUri="{Binding}" RequestNavigate="Hyperlink_RequestNavigate">
<TextBlock Text="{Binding}" />
</Hyperlink>
</TextBlock>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>

关于wpf - 绑定(bind)到带有可点击链接的列表框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4483841/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com