我在WPF列表框上使用交替的颜色行(第一行白色和第二个灰色)并向上/向下移动行功能。已经实现了但是当我将第二行移动到第一个位置时背景变为灰色同样,如果从第二行向上移动位置后第一种颜色为灰色,则通过单击向下移动按钮,背景颜色再次变为白色。此行为在上面的行数上无法观察到2.如果我将位置3和4向上移动/向下只有行内容上下移动背景颜色保持固定。我无法找到这种奇怪行为的原因。任何帮助都将不胜感激。
XAML的代码片段
<Style x:Key="AlternatingListViewItemStyle" TargetType="{x:Type ListBoxItem}">
<Style.Triggers>
<Trigger Property="ItemsControl.AlternationIndex" Value="0">
<Setter Property="Background" Value="White"/>
</Trigger>
<Trigger Property="ItemsControl.AlternationIndex" Value="1">
<Setter Property="Background" Value="Gray"/>
</Trigger>
</Style.Triggers>
</Style>
<ListBox ItemsSource="{Binding CollectioNames}" x:Name="listBox" ItemContainerStyle="{StaticResource AlternatingListViewItemStyle}" AlternationCount="2" SelectionMode="Multiple" >
<ListBox.ItemTemplate >
<DataTemplate >
<Grid Margin="0" HorizontalAlignment="Stretch" VerticalAlignment="Top">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="200*" MinWidth="200" ></ColumnDefinition>
<ColumnDefinition Width="Auto"></ColumnDefinition>
<ColumnDefinition Width="Auto" ></ColumnDefinition>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition></RowDefinition>
</Grid.RowDefinitions>
<CheckBox x:Name="checkBoxList" Grid.Row="0" Grid.Column="0" IsChecked="{Binding IsChecked}" Content="{Binding Path=Item.Name}" />
<Button x:Name="btnListUp" Grid.Row="0" Grid.Column="1" Click="moveUp_Click" Content="Ç" FontFamily="Wingdings 3" VerticalAlignment="Stretch" />
<Button x:Name="btnListDown" Grid.Row="0" Grid.Column="2" Click="moveDown_Click" FontFamily="Wingdings 3" Content="È" VerticalAlignment="Stretch" />
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
代码背后的代码
public ObservableCollection<CheckedListItem<MyClass>> CollectioNames { get; set; }
private void moveUp_Click(object sender, RoutedEventArgs e)
{
try
{
Button button = sender as Button;
var dataContext = button.DataContext;
CheckedListItem<MyClass> selectedfile = button.DataContext as CheckedListItem<MyClass>;
int index = CollectioNames.IndexOf(selectedfile);
if (index > 0)
{
CollectioNames.Move(index, index - 1);
}
}
catch (Exception ex)
{
}
}
private void moveDown_Click(object sender, RoutedEventArgs e)
{
try
{
Button button = sender as Button;
var dataContext = button.DataContext;
CheckedListItem<MyClass> selectedfile = button.DataContext as CheckedListItem<MyClass>;
int index = CollectioNames.IndexOf(selectedfile);
if (index < CollectioNames.Count - 1)
{
CollectioNames.Move(index, index + 1);
}
}
catch (Exception ex)
{
}
}