我有一个列表框,其中我有一个ItemTemplate,而在ItemTemplate中我有一个DataTemplate,我有一个Canvas作为一个按钮,所以我的要求是当一个项目即Canvas被选中时应该更改背景,默认情况下选择应该是第一个项目,当选择被更改时,我需要相应地更改选定的画布背景颜色我如何才能实现这一目标,寻求真正的帮助,提前谢谢。
我试过以下代码: -
这是我的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>
这就是我在我的代码背后所尝试的: -
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();
}
}