单击列表视图中自定义控件上的事件,但不总是设置SelectedItem

本文关键字:SelectedItem 设置 事件 视图 列表 自定义控件 单击 | 更新日期: 2025-03-17 21:34:51

我有一个列表视图的情况:

<ListView ItemsSource="{Binding Environments}" SelectedItem="{Binding SelectedEnvironment}">
    <ListView.ItemTemplate>
        <DataTemplate>
            <controls:RadioButtonTextBox DataContext="{Binding}"/>
         </DataTemplate>
     </ListView.ItemTemplate>
 </ListView>

它使用自定义控件作为其项目模板:

<StackPanel Orientation="Horizontal">
    <RadioButton VerticalAlignment="Center">
        <RadioButton.IsChecked>
            <MultiBinding Converter="{converters:StringCompareToBooleanConverter}">
                <Binding Path="." RelativeSource="{RelativeSource Mode=FindAncestor, AncestorType=UserControl}"/>
                <Binding Path="SelectedItem" RelativeSource="{RelativeSource Mode=FindAncestor, AncestorType=ListView}"/>
            </MultiBinding>
        </RadioButton.IsChecked>    
    </RadioButton>
    <TextBlock Text="{Binding}" VerticalAlignment="Center" Margin="5,0,0,0" Style="{DynamicResource RedTextBlock}"/>
</StackPanel>

我遇到的问题是,如果用户单击自定义控件的文本块,那么正确的事情就会发生,即项目被选中(视图模型也会相应地更新),但如果用户单击了自定义控件的单选按钮,则单选按钮会被选中,但所选项目不会更新,之前选择的项目也不会被取消选择。

有人能帮我解决这个问题吗?

单击列表视图中自定义控件上的事件,但不总是设置SelectedItem

单击由单选按钮处理而不是传播。

在项目包含输入元素的情况下,我倾向于将ItemContainerStyle中的IsSelected绑定到IsKeyboardFocusWithin。不确定这是否取消选择旧项目,可能仅当选择模式为Single时。

我发现的最简单的解决方案是简单地将单选按钮上的enabled标志设置为false:

 <StackPanel Orientation="Horizontal">
    <RadioButton VerticalAlignment="Center" IsEnabled="False">
        <RadioButton.IsChecked>
            <MultiBinding Converter="{converters:StringCompareToBooleanConverter}">
                <Binding Path="." RelativeSource="{RelativeSource Mode=FindAncestor, AncestorType=UserControl}"/>
                <Binding Path="SelectedItem" RelativeSource="{RelativeSource Mode=FindAncestor, AncestorType=ListView}"/>
            </MultiBinding>
        </RadioButton.IsChecked>    
    </RadioButton>
    <TextBlock Text="{Binding}" VerticalAlignment="Center" Margin="5,0,0,0" Style="{DynamicResource RedTextBlock}"/>
</StackPanel>