首页 > 解决方案 > 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向它们添加(不同的)工具提示?或者,我可以使用什么其他控件来实现这一点?

标签: c#wpflistview

解决方案


设置ToolTipfromItemContainerStyle并将其绑定到项目,然后使用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();
}

推荐阅读