【问题标题】:Delete Button for each ListView Row每个 ListView 行的删除按钮
【发布时间】:2014-04-07 13:28:53
【问题描述】:

我有一个绑定到 Observable Collection 'People' 的列表视图,People 包含具有属性 'Name' 的人员,这给了我一张人员表。

我希望该表的每一行都有一个删除按钮,出现在最后一列。下面是一个工作实现。然而,处理程序和 XAML 非常交织在一起,这并不好。我怎么能传递我删除的人的哪个成员?

XAML:

 <ListView ItemsSource="{Binding People}" Name="ListViewPeople">
                        <ListView.View>
                            <GridView>
                                <GridViewColumn>
                                    <GridViewColumnHeader>Names</GridViewColumnHeader>
                                    <GridViewColumn.CellTemplate>
                                        <DataTemplate>
                                            <TextBox Text="{Binding Names}"></TextBox>
                                        </DataTemplate>
                                    </GridViewColumn.CellTemplate>
                                </GridViewColumn>
                                <GridViewColumn>
                                    <GridViewColumn.CellTemplate>
                                        <DataTemplate>
                                            <Button Content="Delete" Click="Button_Click_Delete"/>
                                        </DataTemplate>
                                    </GridViewColumn.CellTemplate>
                                </GridViewColumn>
                            </GridView>
                        </ListView.View>
                 </ListView>

我已经设法用这个处理程序实现了这一点,但正如您所见,这意味着支持代码必须详细了解视图。这将获取从 ListView 中按下的删除按钮的索引,然后从我的可观察集合中删除该值。

c#代码:

    private void Button_Click_Delete(object sender, RoutedEventArgs e)
    {
        DependencyObject dep = (DependencyObject)e.OriginalSource;

        while ((dep != null) && !(dep is ListViewItem))
        {
            dep = VisualTreeHelper.GetParent(dep);
        }

        if (dep == null)
            return;

        int index = ListViewPeople.ItemContainerGenerator.IndexFromContainer(dep);

        People.RemoveAt(index);
    }

有没有办法将我已删除的可观察集合的哪个成员传递给我的处理程序,以便处理程序不必知道存在列表视图等?

【问题讨论】:

  • 尝试像这样 DataContext="{Binding}" 对 DataContext 进行绑定,然后单击检查 DataContext 中的内容。当您拥有对象时,您可以将其移除
  • 你知道命令和命令参数吗..

标签: c# wpf mvvm


【解决方案1】:
Button btn = (Button)sender;
People.Remove((Person)btn.DataContext);

【讨论】:

  • FrameworkElement btn = (FrameworkElement)sender; mInfoBean.Remove((DocBeanInfoView)btn.DataContext);似乎可以解决问题。比我的实现要好得多,谢谢。我已经多看了一点 MVVM,它根本不喜欢点击处理程序,所以我现在可能会使用它并坚持使用旧方法。
猜你喜欢
  • 2013-04-17
  • 2017-07-20
  • 2013-07-05
  • 2013-02-28
  • 1970-01-01
  • 1970-01-01
  • 2019-05-28
  • 2015-02-03
  • 2011-03-03
相关资源
最近更新 更多