【问题标题】:WPF CommandParameter RelativeSource BindingWPF 命令参数相对源绑定
【发布时间】:2019-06-03 22:34:27
【问题描述】:

我在 ListView 的 DataTemple 中有一个带有 CheckBox 的 ListView。我被展示了如何使命令工作。我想捕获 ListView SelectedItem 作为参数传递给命令,但我没有正确...

<ListView x:Name="lvReferralSource" ItemsSource="{Binding ReferralObsCollection}" Style="{StaticResource TypeListViewStyle}">
                            <ListView.ItemTemplate>
                                <DataTemplate>
                                    <Grid Width="200">
                                        <Grid.ColumnDefinitions>
                                            <ColumnDefinition Width="*"/>
                                            <ColumnDefinition Width="Auto"/>
                                        </Grid.ColumnDefinitions>

                                        <CheckBox x:Name="ckbReferralIsChecked" Content="{Binding Value}" IsChecked="{Binding Active}" Style="{StaticResource CheckBoxStyleBase2}"
                                                  Command="{Binding DataContext.CheckBoxIsChecked, RelativeSource={RelativeSource AncestorType=ListView}}" 
                                                  CommandParameter="{Binding RelativeSource={RelativeSource AncestorType=ListView}, Path=SelectedItem}">
                                        </CheckBox>
                                    </Grid>
                                </DataTemplate>
                            </ListView.ItemTemplate>
                        </ListView>

【问题讨论】:

  • 在您的情况下,所选项目是复选框项目,不是吗,因为只有复选框作为列表视图项目存在,如果您这样做,它将通过复选框的内容作为参数CommandParameter="{Binding RelativeSource={RelativeSource Self},Path=Content}"
  • @mjordan:如果选择了一个项目,您当前的绑定应该可以工作。但是,您为什么不简单地绑定到 current 项,而不管它是否实际被选中? CommandParameter="{Binding}".
  • 我也是这么想的,但我认为由于他有 2 列,他计划稍后在那里添加其他内容,例如,如果从列表中选择复选框变为启用

标签: wpf command commandparameter


【解决方案1】:

再看这个问题,我想我现在理解正确了。 这是从ListView 获取SelectedItem 的不同方法 然后在CheckBox我绑定CommandParameter如下

CommandParameter="{Binding ElementName=lvReferralSource, Path=SelectedItem}"

下面会传递CheckBox相关的对象

CommandParameter="{Binding}"// Full object from the ListView

在与CheckBox相关的Command Method中,您可以将参数对象转换为正确的类型(ListView ItemSource中的对象类型)并获取ValueActive的值

【讨论】:

  • 谢谢。看起来它应该可以工作,但是“null”被传递给了参数。我正在尝试从复选框中获取“值”和“活动”属性。
  • 它从列表的 ItemSource 中传递相关的选定对象,如果它为 null,则说明您尚未选择项目或 ItemSource 中的对象为 null
  • 您可以从 SelectedItem 中访问 Value 吗?
  • 谢谢!第二个选项效果很好。传递对象。
猜你喜欢
  • 1970-01-01
  • 2010-12-21
  • 1970-01-01
  • 2018-11-27
  • 1970-01-01
  • 2011-01-10
  • 2016-05-07
  • 2016-08-21
  • 2015-10-04
相关资源
最近更新 更多