I have a class ExpanderItems
which gets loaded during runtime and a list of these is set as the DataContext
of a ListBox
. Now what I want to do is show the corresponding Images as a Tooltip
for each Item. Any suggestions how to do that?
public class ExpanderItem
{
private String mItemName = "empty";
public String ItemName
{
get { return mItemName; }
set { mItemName = value; }
}
private Image mItemSymbol = null;
public Image ItemSymbol
{
get { return mItemSymbol; }
set { mItemSymbol = value; }
}
}
public List<ExpanderItem> getExpanderItems()
{
List<ExpanderItem> ItemList = new List<ExpanderItem>();
ExpanderItem i0 = new ExpanderItem();
i0.ItemName = "Constant";
i0.ItemSymbol = new Image();
BitmapImage bi = new BitmapImage();
bi.BeginInit();
bi.UriSource = new Uri(@"/resources/Constant.png", UriKind.RelativeOrAbsolute);
bi.EndInit();
i0.ItemSymbol.Source = bi;
ItemList.Add(i0);
...
}
In the Window where the Items are used I am calling:
void WindowMain_Loaded(object sender, RoutedEventArgs e)
{
lbItems.DataContext = SomeService.getExpanderItems();
}
XAML Looks like:
<ListBox x:Name="lstItems" ItemsSource="{Binding}">
<ListBox.ItemTemplate>
<DataTemplate>
<Label Content="{Binding ItemName}">
</Label>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Compiled and tested solution.
XAML:
<ListBox x:Name="lb"
ItemsSource="{Binding}"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch">
<ListBox.ItemContainerStyle>
<Style TargetType="{x:Type ListBoxItem}">
<Setter Property="ToolTip">
<Setter.Value>
<Image Stretch="UniformToFill"
Source="{Binding ItemSymbol}" />
</Setter.Value>
</Setter>
</Style>
</ListBox.ItemContainerStyle>
<ListBox.ItemTemplate>
<DataTemplate>
<Label Grid.Column="1"
Content="{Binding ItemName}">
</Label>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Code:
using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Media.Imaging;
namespace Test
{
public class ExpanderItem
{
private String mItemName = "empty";
public String ItemName
{
get { return mItemName; }
set { mItemName = value; }
}
private BitmapImage mItemSymbol = null;
public BitmapImage ItemSymbol
{
get { return mItemSymbol; }
set { mItemSymbol = value; }
}
}
public partial class MainWindow : Window
{
public MainWindow()
{
this.InitializeComponent();
lb.DataContext = this.getExpanderItems();
}
public List<ExpanderItem> getExpanderItems()
{
List<ExpanderItem> ItemList = new List<ExpanderItem>();
ExpanderItem i0 = new ExpanderItem
{
ItemName = "Constant",
ItemSymbol = new BitmapImage(new Uri(@"/resources/constant.png", UriKind.RelativeOrAbsolute))
};
ItemList.Add(i0);
ExpanderItem i1 = new ExpanderItem
{
ItemName = "Constant",
ItemSymbol = new BitmapImage(new Uri(@"/resources/constant.png", UriKind.RelativeOrAbsolute))
};
ItemList.Add(i1);
return ItemList;
}
}
}