【问题标题】:Click event on custom control in list view not always setting SelectedItem列表视图中自定义控件上的单击事件并不总是设置 SelectedItem
【发布时间】:2016-05-10 22:23:34
【问题描述】:

我有一个列表视图:

<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>

我遇到的问题是,如果用户单击自定义控件的文本块,则会发生正确的事情,即选择项目(并且视图模型会相应更新),但是如果用户单击单选按钮自定义控件的单选按钮变为选中状态,但所选项目未更新,并且先前选择的项目未取消选择。

谁能帮忙解决这个问题?

【问题讨论】:

    标签: c# wpf xaml


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      我找到的最简单的解决方案是简单地将单选按钮上的启用标志设置为 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>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-29
        • 1970-01-01
        • 2015-07-16
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多