简体   繁体   English

将列表框selectedItems从一个WPF页面发送到另一页面

[英]Send listbox selecteditems from one wpf page to another

I am trying to select items from listbox 1 on mainpage, click a button called add and send the items to a new page. 我试图从主页上的列表框1中选择项目,单击名为添加的按钮,然后将项目发送到新页面。 But i am dont think my method in doing so is right. 但是我不认为我的方法是正确的。

MainPage.xaml.cs MainPage.xaml.cs

private void btnAdd_Click(object sender, RoutedEventArgs e)
    {

        List<Names> tmp = new List<Names>();

         foreach(var names in lstNames.SelectedItems)
         {
             tmp.Add(names);
         }
         lstNames.ItemsSource = tmp;

        Frame.Navigate(typeof(Page2), tmp);

    }

Page2.xaml.cs Page2.xaml.cs

protected override void OnNavigatedTo(NavigationEventArgs e)
    {
        base.OnNavigatedTo(e);

        var tmp = (Names)e.Parameter;

        lstNames2.ItemsSource = tmp;
    }
}

Any guidance is appreciated on how I do this. 我如何做到这一点的任何指导表示赞赏。

The object you pass as the second parameter ends up in the ExtraData property of the NavigationEventArgs. 您作为第二个参数传递的对象最终位于NavigationEventArgs的ExtraData属性中。

private void btnAdd_Click(object sender, RoutedEventArgs e)
{
     var tmp = lstNames.SelectedItems.ToList();
     Frame.Navigate(typeof(Page2), tmp);
}

I'm using Linq for the ToList() there. 我在那里使用Linq作为ToList()。

protected override void OnNavigatedTo(NavigationEventArgs e)
{
    base.OnNavigatedTo(e);
    lstNames2.ItemsSource = e.ExtraData as List<Name>;
}

I recommend you look at MVVM though. 我建议您虽然看一下MVVM。 The way I would do this is an approach called viewmodel first. 我这样做的方法是首先称为viewmodel的方法。 I'd use a contentcontrol rather than a frame and have usercontrols rather than pages in it. 我将使用contentcontrol而不是框架,并在其中使用usercontrol而不是页面。 I'd use templating to template a viewmodel into a page-equivalent usercontrol. 我将使用模板将视图模型模板化成与页面等效的用户控件。

Passing the list would be into the constructor of the viewmodel I "navigate" to. 将列表传递到我“导航”到的视图模型的构造函数中。 It's a standard wpf technique you should be able to easily google. 这是一种标准的WPF技术,您应该可以轻松地使用Google。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM