gpt4 book ai didi

c# - WP7 ListBox 选中的项目没有改变颜色

转载 作者:太空宇宙 更新时间:2023-11-03 16:04:22 29 4
gpt4 key购买 nike

我在应用程序中有一个列表框,里面有一个图像和一个文本框。我想为所选项目设置 2 种颜色和第 3 种颜色。

<ListBox.ItemTemplate>
<DataTemplate x:Name="Template1">
<StackPanel Orientation="Horizontal" >
<Image Width="100" Height="100" Source="{Binding SmallImage}"></Image>
<Grid>
<TextBlock Text="{Binding Caption}" Foreground="{Binding txtColor}"></TextBlock>
</Grid>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>

当我更改前景色时,所选项目不会突出显示(我默认保留它)。我试图向 ListBox 添加一个事件,

private void DList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ListBoxItem selectedItem = DList.SelectedItem as ListBoxItem;

selectedItem.Foreground = new SolidColorBrush(Colors.Red);

}

但它显示了一个异常:空引用异常“使用‘new’关键字创建对象实例”

最佳答案

如果您要处理 SelectionChanged 事件,那么您不妨使用 SelectionChangedEventArgs对象:

private void DList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var selectedDataObject = e.AddedItems[0]; // assuming single selection
ListBoxItem selectedItem =
ListBoxName.ItemContainerGenerator.ContainerFromItem(selectedDataObject);
selectedItem.Foreground = new SolidColorBrush(Colors.Red);
}

关于c# - WP7 ListBox 选中的项目没有改变颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20003028/

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