[英]WPF ListView Change Selected Item on ComboBox cell item focus or change
對於ListView,行中有多個組合框。 我還具有綁定到所選行的文本框,以顯示ListView下一行的其他信息。 問題在於,當您單擊一行中的ComboBox時,該行的ListView所選項目/索引不會更改。 選擇該行中的ComboBox時,如何更改該行在ListView中的所選項目?
這是我的ComboBox ListView:
<ListView Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="4" VerticalAlignment="Stretch"
ItemsSource="{Binding Equations.DataExpressions}" SelectedItem="{Binding Equations.SelectedExpression}" SelectedIndex="0">
<ListView.Resources>
<Style TargetType="{x:Type ListViewItem}">
<Setter Property="HorizontalContentAlignment" Value="Stretch" />
<Setter Property="VerticalContentAlignment" Value="Stretch" />
<Style.Triggers>
<DataTrigger Binding="{Binding IsValidExpression}" Value="false">
<Setter Property="Background" Value="#FF8080" />
</DataTrigger>
</Style.Triggers>
</Style>
</ListView.Resources>
<ListView.View>
<GridView>
<GridViewColumn Header="Path" Width="90">
<GridViewColumn.CellTemplate>
<DataTemplate>
<ComboBox ItemsSource="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=DataContext.PathItems}"
SelectedValue="{Binding EvaluatedPath}" Margin="-6, 0, -6, 0" VerticalAlignment="Stretch" HorizontalAlignment="Stretch">
</ComboBox>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
</GridView>
</ListView.View>
將事件處理程序添加到您的Style
並處理PreviewMouseLeftButtonDown
事件:
private void lv_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
ListViewItem lvi = (ListViewItem)sender;
ListView lv = FindParent<ListView>(lvi);
lv.SelectedItem = lvi.DataContext;
}
private static T FindParent<T>(DependencyObject dependencyObject) where T : DependencyObject
{
var parent = VisualTreeHelper.GetParent(dependencyObject);
if (parent == null) return null;
var parentT = parent as T;
return parentT ?? FindParent<T>(parent);
}
XAML:
<Style TargetType="{x:Type ListViewItem}">
<Setter Property="HorizontalContentAlignment" Value="Stretch" />
<Setter Property="VerticalContentAlignment" Value="Stretch" />
<EventSetter Event="PreviewMouseLeftButtonDown" Handler="lv_PreviewMouseLeftButtonDown" />
<Style.Triggers>
<DataTrigger Binding="{Binding IsValidExpression}" Value="false">
<Setter Property="Background" Value="#FF8080" />
</DataTrigger>
</Style.Triggers>
</Style>
請注意,由於這純粹是與視圖/控件相關的邏輯,因此應在視圖中(代碼背后)實現。 視圖模型不負責控件的行為,因此不會破壞MVVM模式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.