我有一个列表视图,显示在用户界面上看不到的驱动程序。通过使用此列表视图,可以再次显示它们。功能完美,但为了给最终用户一些清晰的选择驱动程序,我想将listviewitem的背景颜色更改为黄色(例如)。如果他们再次选择此listviewitem,我想将背景颜色更改为正常。
这是我视图中的代码:
<ListView Margin="10,10,10,10" x:Name="lstViewCollapsedDrivers" ItemsSource="{Binding CollapsedDrivers}" Grid.Row="1" Grid.Column="2"
ScrollViewer.CanContentScroll="True" ScrollViewer.VerticalScrollBarVisibility="Auto" SelectionChanged="LstViewCollapsedDrivers_OnSelectionChanged">
<i:Interaction.Triggers>
<i:EventTrigger SourceName="lstViewCollapsedDrivers" EventName="MouseUp">
<i:InvokeCommandAction Command="{Binding SelectCollapsedDriverCommand}" CommandParameter="{Binding ElementName=lstViewCollapsedDrivers, Path=SelectedItem}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
<ListView.ItemContainerStyle>
<Style TargetType="ListViewItem">
<Setter Property="Height" Value="50"/>
<Style.Triggers>
<DataTrigger Binding="{Binding Path=RowSelected}" Value="True">
<Setter Property="Background" Value="Yellow"/>
</DataTrigger>
</Style.Triggers>
</Style>
</ListView.ItemContainerStyle>
<ListView.View>
<GridView>
<GridViewColumn DisplayMemberBinding="{Binding Name}">
<GridViewColumnHeader Style="{StaticResource gridViewColumnHeaderStyle}" Content="Name"/>
</GridViewColumn>
<GridViewColumn DisplayMemberBinding="{Binding Haulier}">
<GridViewColumnHeader Style="{StaticResource gridViewColumnHeaderStyle}" Content="Haulier"/>
</GridViewColumn>
<GridViewColumn DisplayMemberBinding="{Binding Plate}">
<GridViewColumnHeader Style="{StaticResource gridViewColumnHeaderStyle}" Content="Plate"/>
</GridViewColumn>
<GridViewColumn DisplayMemberBinding="{Binding Telephone}">
<GridViewColumnHeader Style="{StaticResource gridViewColumnHeaderStyle}" Content="Telephone"/>
</GridViewColumn>
</GridView>
</ListView.View>
</ListView>
问题是,ListView.Items现在是Driver类型而不是ListViewItem(我认为是这样的:ItemsSource =“{Binding CollapsedDrivers}”)。我尝试了很多东西,但我没办法将这些项解析回ListViewItems。
我还添加了一些代码(实际上我试图避免这种情况,但如果没有别的办法......)。
private void LstViewCollapsedDrivers_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
{
var test = sender as ListView;
var lstviewItem = test.SelectedItem ; // This is of type driver...
}
private void LstViewCollapsedDrivers_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
{
var test = sender as ListView;
var lstviewItem = test.SelectedItem as ListViewItem; // This is null...
}
任何人都知道如何解决这个问题?谢谢:))
答案 0 :(得分:2)
您可以使用ItemContainerGenerator.ContainerFromItem
方法从ListViewItem
对象生成Driver
:
private void OnSelectionChanged(object sender, SelectionChangedEventArgs e)
{
ListView listView = sender as ListView;
Driver selectedDriver = listView.SelectedItem ;
ListViewItem item = (ListViewItem)
listView.ItemContainerGenerator.ContainerFromItem(selectedDriver);
}