【问题标题】:Getting the SelectedItem in a ListBox with itemtemplate that contains only a button使用仅包含一个按钮的 itemtemplate 获取 ListBox 中的 SelectedItem
【发布时间】:2017-10-08 13:40:54
【问题描述】:

这两天我一直在尝试解决这个问题。 我有一个绑定到 ObservableCollection 的 ListBox。 ListBox 使用模板为集合中的每个项目显示一个 Button。我想在单击按钮时触发命令并将 selectedItem 作为参数传递。

问题是当我单击按钮时,列表框的 SelectedItem 为空,列表框永远不会获得焦点来更改其选择。从我在 SO 中找到的按钮单击事件正在中断 ListBox SelectionChanged。 这是列表框的 XAML,我的视图模型使用 Prism 6.3 DelegateCommand 发布事件。

<ListBox Name="PatientsListBox" 
         ItemsSource="{Binding Patients}" 
         SelectedItem="{Binding SelectedPatient}"
         HorizontalContentAlignment="Stretch"
         >

        <ListBox.ItemTemplate>
            <DataTemplate>
                <Grid>
                    <Button Content="{Binding Path=Name}" 
                            Background="{Binding Path=Sex, Converter={StaticResource ColorConverter}}" 
                            Margin="0" Padding="0" 
                            Width="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListBox}}, Path=ActualWidth, Mode=OneWay}" 
                            Command="{Binding ElementName=LayoutRoot, Path=DataContext.ShowPatientCommand}" 
                            CommandParameter="{Binding ElementName=PatientsListBox, Path=SelectedItem}">
                    </Button>
                </Grid>
            </DataTemplate>
        </ListBox.ItemTemplate>
        <ListBox.ItemContainerStyle>
            <Style TargetType="ListBoxItem">
                <Setter Property="HorizontalContentAlignment" Value="Stretch"></Setter>
            </Style>
        </ListBox.ItemContainerStyle>
    </ListBox>

是否可以在不使用代码的情况下仅使用 XAML 来做到这一点?

我尝试使用 ItemsControl,但它没有 SelectedItem 属性。 我也尝试过使用 textBlock 模板的交互性,但该命令从未触发。

有什么想法吗?

【问题讨论】:

    标签: c# wpf mvvm prism-6


    【解决方案1】:

    终于在MSDN论坛Here is the full thread找到了答案。我将我的 CommandParameter 绑定更改为以下

    CommandParameter="{Binding}"
    

    这指示 WPF 命令管理器使用 DataTemplate 的绑定项。米格尔·费尔南德斯畜栏

    就是这样。我希望这对将来的某人有所帮助。 干杯

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-04-25
      • 2014-08-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多