[英]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.