WP7 ListBox所选项目未更改颜色 [英] WP7 ListBox selected item is not changing the color
本文介绍了WP7 ListBox所选项目未更改颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在应用程序中有一个ListBox,它里面有一个图像和文本框.我要为所选项目设置2种颜色和第3种颜色.
I have a ListBox in app, it has an image and textbox inside. I want to set 2 colors and 3rd one for selected item.
<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,
when I'm changing the foreground color, then the selected item doesn't highlights (I kept it by default). I tried to add an event to ListBox,
private void DList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ListBoxItem selectedItem = DList.SelectedItem as ListBoxItem;
selectedItem.Foreground = new SolidColorBrush(Colors.Red);
}
,但显示异常: NullReferenceException 使用"new"关键字创建对象实例"
but it shows an exception: NullReferenceException "Use the "new" keyword to create an object instance"
推荐答案
If you're going to handle the SelectionChanged
event, then you might as well use the SelectionChangedEventArgs
object:
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);
}
这篇关于WP7 ListBox所选项目未更改颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文