如何在WP8中更改列表框中选定项的背景颜色和文本块内容的颜色

本文关键字:颜色 背景 文本 WP8 列表 | 更新日期: 2023-09-27 18:07:31

我在Windows phone 8应用程序上工作。我使用一个列表框来动态显示列表,并在列表框中选择更改一个项目,我想选择的项目背景颜色为蓝色,文本块文本颜色为白色(仅适用于所选项目)这是listbox

的xaml代码
<Canvas  x:Name="Canvas_Main" Margin="23,191,27,75" Tap="Canvas_Main_Tap">
        <ListBox x:Name="Listbox_Main" Height="534" Width="430" ItemsSource="{Binding}" SelectionChanged="Listbox_Main_SelectionChanged" Tap="Listbox_Main_Tap" Canvas.Left="10"  >
            <ListBox.ItemsPanel>
                <ItemsPanelTemplate>
                    <toolkit:WrapPanel/>
                </ItemsPanelTemplate>
            </ListBox.ItemsPanel>
            <ListBox.ItemContainerStyle>
                <Style TargetType="ListBoxItem">
                    <Setter Property="Padding" Value="5"/>
                </Style>
            </ListBox.ItemContainerStyle>
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <Canvas x:Name="cnv_Items" Height="100" Width="200">
                        <Border Height="100" Width="200" BorderThickness="2" BorderBrush="#FFD0D0D0"/>
                        <TextBlock x:Name="Tb_Value" Text="{Binding Value}" TextWrapping="NoWrap" Foreground="Black" TextAlignment="Right" FontSize="26" Height="40" Width="195" Canvas.Top="10" Canvas.Left="2"/>
                        <TextBlock x:Name="Tb_UnitName" Text="{Binding Key}" Foreground="Black" TextAlignment="Right" FontSize="19" Height="40" Width="180" Canvas.Top="55" Canvas.Left="10"/>
                    </Canvas>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
    </Canvas>

Its my Code Behind:-

private void Listbox_Main_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (Canvas_KeyBoard.Visibility == Visibility.Visible)
                OutAnimation();
            if (Listbox_Main.SelectedItem != null)
            {
                myitem = (KeyValuePair<string, string>)Listbox_Main.SelectedItem;
                ListBoxItem myitem1 = Listbox_Main.SelectedItem as ListBoxItem;
                SolidColorBrush brush = new SolidColorBrush(Color.FromArgb(255, 255, 0, 0));
                myitem1.Background = brush;
                Conversion_Logic();
            }
        }

请告诉我该怎么做,我在这个问题上工作了2天,但无法得到解决方案。希望大家帮帮我

如何在WP8中更改列表框中选定项的背景颜色和文本块内容的颜色

既然你的ListBox有一个selectionchanged事件,你可以试试这个。最好的解决方案是使用样式和触发器

    private void Listbox_Main_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        ListBoxItem myitem = Listbox_Main.SelectedItem as ListBoxItem;
        SolidColorBrush brush =  new SolidColorBrush(Color.FromArgb(255,255,0,0));
        myitem.Background = brush;
    }