我有一个ListView,它使用数据模板显示单元格中的特定控件:
<ListView Grid.Row="1" ItemsSource="{Binding Ratings}" SelectedItem="{Binding SelectedRating}" Margin="5" MinHeight="50" SelectionMode="Single" ScrollViewer.CanContentScroll="True"
local:GridViewSort.Enable="True">
<ListView.View>
<GridView>
<GridViewColumn Header="Date" local:GridViewSort.PropertyName="RatingDate">
<GridViewColumn.CellTemplate>
<DataTemplate>
<DatePicker SelectedDate="{Binding RatingDate}"/>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn Header="Rating ID" local:GridViewSort.PropertyName="RatingID">
<GridViewColumn.CellTemplate>
<DataTemplate>
<TextBox Text="{Binding RatingID}" Width="35" />
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn Header="Name" local:GridViewSort.PropertyName="RatingName">
<GridViewColumn.CellTemplate>
<DataTemplate>
<TextBox Text="{Binding RatingName}" Width="35" />
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn Header="Age" local:GridViewSort.PropertyName="RatingAge">
<GridViewColumn.CellTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBox Text="{Binding RatingAge}" Width="35" />
<TextBlock Text=" yrs"/>
</StackPanel>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
</GridView>
</ListView.View>
</ListView>
我还有一个删除按钮来删除所选行。
我的用户习惯点击编辑和日期控件(不会更改所选行),然后点击删除以删除他点击的行。不幸的是,这会删除错误的行。
每当用户点击控件时,如何更改行选择?
答案 0 :(得分:2)
您可以在ListViewItem上使用PreviewMouseUp事件:
<ListView Grid.Row="1" ItemsSource="{Binding Ratings}" SelectedItem="{Binding SelectedRating}" Margin="5" MinHeight="50" SelectionMode="Single" ScrollViewer.CanContentScroll="True"
local:GridViewSort.Enable="True">
<ListView.Resources>
<Style TargetType="{x:Type ListViewItem}">
<EventSetter Event="PreviewMouseUp" Handler="ListViewItem_PreviewMouseUp" />
</Style>
</ListView.Resources>
<ListView.View>
<GridView>
...
代码背后:
private void ListViewItem_PreviewMouseUp(object sender, MouseButtonEventArgs e)
{
var listViewItem = sender as ListViewItem;
if (listViewItem != null)
{
listViewItem.IsSelected = true;
}
}