WP7 ListBox selected item is not changing the color

故事扮演 提交于 2019-12-24 01:19:48

问题


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>

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);

    }

but it shows an exception: NullReferenceException "Use the "new" keyword to create an object instance"


回答1:


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);
}


来源:https://stackoverflow.com/questions/20003028/wp7-listbox-selected-item-is-not-changing-the-color

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!