【问题标题】:getting items from context menu in binding listview WPF c#从绑定listview WPF c#中的上下文菜单中获取项目
【发布时间】:2015-11-18 13:12:13
【问题描述】:

我是 Microsoft Visual Studio WPF C# 的新手.. 我编写的代码显示了用于绑定列表视图的上下文菜单,当我们右键单击列表中的项目时,它将删除它...... 我想在我们删除它之前获取它的值

**xaml

<ListView Name="listview1" HorizontalAlignment="Left" Height="350" Margin="251,63,0,0" VerticalAlignment="Top" Width="214" FontSize="16" FontWeight="Bold">
        <ListView.ContextMenu>
            <ContextMenu>
                <MenuItem Header="Remove"
                Click="MenuItemDelete_Click" 
        Command="{Binding RemoveItem}"
        CommandParameter="{Binding RelativeSource={RelativeSource AncestorType=ContextMenu}, Path=PlacementTarget.SelectedItem}" />
            </ContextMenu>

        </ListView.ContextMenu>
        <ListView.View>
            <GridView>
                <GridView.Columns>

                    <GridViewColumn x:Name="Dtime" DisplayMemberBinding=
                      "{Binding Path=Dtime}" 
                  Header=" Date" Width="120"/>
                    <GridViewColumn x:Name="Patient"  DisplayMemberBinding=
                      "{Binding Path=Patient}"   
                  Header="Patient" Width="80"/>
                </GridView.Columns>
            </GridView>
        </ListView.View>

**代码

 class myresult {

        public String Dtime{ get; set; }
        public String Patient{ get; set; }

    }




 private void MenuItemDelete_Click(object sender, RoutedEventArgs e)
    {

            if (listview1.SelectedIndex == -1)
            {
                return;
            }

// here I will get the Item I want but I cant get the value inside the item                 

       var asw = listview1.Items.GetItemAt(listview1.SelectedIndex);



        listview1.Items.RemoveAt(listview1.SelectedIndex);
    }

【问题讨论】:

    标签: c# wpf listview visual-studio-2012 contextmenu


    【解决方案1】:

    您可以获取SelectedItem 的DataContext 并将其转换为myresult 对象。

    myresult result = ((FrameworkElement)listview1.SelectedItem).DataContext as myresult;
    

    或者,您可以使用之前使用的相同SelectedIndex 方法。

    myresult result = ((FrameworkElement)asw).DataContext as myresult;
    

    【讨论】:

    • 我得到一个错误(无效的转换异常)(无法将 myresult 类型的对象转换为类型(system.windows.FrameworkElement)
    • 从我的示例中,您使用的是哪种方法?看起来您甚至根本不需要转换为 FrameworkElement。如果你使用的是第二种方法,我猜你是,试试这个:myresult result = asw as myresult;。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-03
    相关资源
    最近更新 更多