c# - ListView 元素的代码隐藏工具提示
问题描述
我有一个ListView
在代码隐藏中填充的,如下所示:
<ListView x:Name="FruitListView">
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock FontSize="20" Text="{Binding}"/>
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
<ListView.ItemContainerStyle>
<Style TargetType="ListViewItem">
<Setter Property="HorizontalContentAlignment" Value="Center" />
<Setter Property="Width" Value="146" />
</Style>
</ListView.ItemContainerStyle>
</ListView>
由于我的列表中的水果数量会随着时间而变化,因此必须在后面的代码中动态创建工具提示。
public FruitPage()
{
InitializeComponent();
var Fruits = new List<string>();
Fruits.Add("apple");
Fruits.Add("orange");
// Populate the ListView.
FruitListView.ItemsSource = Fruits;
}
我现在想根据文本在每个 ListViewItems 上创建工具提示(例如,代表“苹果”、“橙色”等的 ListViewItem 的不同工具提示)。
由于ListView
'sItemSource
是动态填充的,我假设这些工具提示也必须在代码隐藏中完成,而不是在 XAML 中。
问题是 - 我怎样才能抓住一个ListViewItem
向它添加工具提示?我尝试了以下代码:
foreach (var item in FruitListView.Items)
{
// item.ToolTip = new ToolTip() { Content = "Test" };
}
...但“项目”是 a string
,而不是ListViewItem
.
如何“抓取”ListViewItem
动态填充的每个 s 以ListView
向它们添加(不同的)工具提示?或者,我可以使用什么其他控件来实现这一点?
解决方案
设置ToolTip
fromItemContainerStyle
并将其绑定到项目,然后使用IValueConverter
(数据转换)根据您的约束提供工具提示值:
<ListBox>
<ListBox.Resources>
<ItemToToolTipConverter x:Key="ItemToToolTipConverter" />
</ListBox.Resources>
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="ToolTip"
Value="{Binding Path=., Converter={StaticResource ItemToToolTipConverter}}"/>
</Style>
</ListBox.ItemContainerStyle>
</ListBox>
class ItemToToolTipConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) =>
value is string stringValue
? stringValue.StartsWith("a", StringComparison.OrdinalIgnoreCase)
? "Fruity begins with 'a'"
: "Some random fruit"
: Binding.DoNothing;
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
=> throw new NotSupportedException();
}
推荐阅读
- python - 在 Altair 中设置 count() 截止值?
- docker - Docker 构建失败,没有名为 pip._vendor 的模块用于气流 1.10.0 和 python 2.7
- spring - Spring Security 中的多个入口点
- c# - 需要 C# WinForms 数据绑定复选框帮助
- java - JSF PROJECT_STAGE 生产和 f:param
- asp.net-core-webapi - 在 ASP.NET Core 2.0 中将 XML 设置为默认输出格式
- java - Java 流和过滤到 Map 产生错误
- jquery - 如何根据从 json 生成的选择列表中选择的选项填充表单(或其他元素)?
- python - 抓取 twitch 目录中剪辑的所有链接
- ruby-on-rails - 难以将 sqlite3 添加到 gemfile