首页 文章

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

提问于
浏览
2

我在应用程序中有一个ListBox,里面有一个图像和文本框 . 我想为所选项目设置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);

    }

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

1 回答

  • 0

    如果您要处理 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);
    }
    

相关问题