我想将图像添加到 ListBox 项。
我有 2 张图片。一个是上箭头,第二个是下箭头
我可以使用 ItemTemplate 分配初始图像说 UpArrow 并将图像添加到它
但是单击排序按钮,我想更改图像。新图像已设置但未在 UI 上更改。
我的窗口代码如下
<Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication1"
Title="Window1" Height="Auto" Width="Auto" Loaded="Window_Loaded">
<Window.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Dictionary1.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Window.Resources>
<Grid Height="Auto" Width="Auto">
<Grid.RowDefinitions>
<RowDefinition></RowDefinition>
<RowDefinition></RowDefinition>
</Grid.RowDefinitions>
<ListBox x:Name="lstBox" ItemsSource="{Binding ListIconDataCollection}" Grid.Row="0" Height="200" Width="200">
<ListBox.ItemTemplate>
<DataTemplate DataType="{x:Type local:ListIconData}">
<Grid Width="Auto" Height="Auto" Background="Transparent" >
<Grid.RowDefinitions>
<RowDefinition></RowDefinition>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="150"></ColumnDefinition>
<ColumnDefinition Width="Auto"></ColumnDefinition>
</Grid.ColumnDefinitions>
<TextBlock Grid.Row="0" Grid.Column="0" HorizontalAlignment="Stretch" Text="{Binding DisplayText}"/>
<Image Grid.Row="0" Grid.Column="1" Source="{Binding Path=ImageSource}" Width="20" HorizontalAlignment="Right"/>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<Button Name="btnSort" Grid.Row="1" Height="40" Margin="0,15,0,0" Content="Sort" Click="btnSort_Click"></Button>
</Grid>
我的表格代码如下
private void Window_Loaded(object sender, RoutedEventArgs e)
{
lstDataToSet.Add(new ListIconData { DisplayText = "Milind", ItemSortDirection = SortDirection.None, ImageSource = (ImageSource)FindResource("ImgUp") });
lstDataToSet.Add(new ListIconData { DisplayText = "Patil", ItemSortDirection = SortDirection.None });
lstBox.ItemsSource = ListIconDataCollection;
}
这是正在执行的表单代码,但 UI 上的图像没有改变
private void btnSort_Click(object sender, RoutedEventArgs e)
{
ListIconData objSelectedItem = (ListIconData)lstBox.SelectedItem;
if (objSelectedItem.ItemSortDirection==SortDirection.None)
{
objSelectedItem.ImageSource = null;
objSelectedItem.ImageSource = (ImageSource)FindResource("ImgDown");
}
}
这是 Dictionary1 资源文件代码
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<ImageSource x:Key="ImgUp">icons/Up.ico</ImageSource>
<ImageSource x:Key="ImgDown">icons/Down.ico</ImageSource>
以下是 ListIconDataClass。这是我绑定到 ListBox 的列表
public class ListIconData
{
public string DisplayText { get; set; }
public SortDirection ItemSortDirection { get; set; }
public ImageSource ImageSource { get; set; }
}
}