我有一个列表 View ,该 View 显示哪些驱动程序在用户界面上不可见。通过使用此列表 View ,可以使它们再次可见。该功能完美运行,但是为了使最终用户更清楚选择了哪些驱动程序,我想将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...
}
有人知道如何解决这个问题吗?谢谢 :)
最佳答案
您可以使用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);
}
关于wpf - ListView.Items在ListView中始终为null作为ListViewItem-WPF,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20346963/