使用MVVM从列表框中获取selecteditem [英] Get selecteditem from listbox using MVVM

查看:121
本文介绍了使用MVVM从列表框中获取selecteditem的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在此项目中使用MVVM,我有一个绑定到一组Customer的列表框.我想创建一个事件,以使用所选元素的ID导航detailsPage:

I'm using MVVM in this project, I have a listbox which bind to a collection of Customers. I want to create an event to navigate a detailsPage using id of the elementselected:

 <ListBox ItemsSource="{Binding Customers}" x:Name="state_list" SelectionChanged="state_list_SelectionChanged">
            <i:Interaction.Triggers>
                <i:EventTrigger EventName="selectionchanged">
                    <cmd:EventToCommand Command="{Binding stateSelectedCommand}" PassEventArgsToCommand="True"  />

                 </i:EventTrigger>
            </i:Interaction.Triggers>
                <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Vertical">
                        <TextBlock Text="{Binding nom}" />
                        <!--TextBlock Text="{Binding LastName}" />
                        <TextBlock Text="{Binding Text, ElementName=tbCount}" /-->
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

我不知道如何获取选定的项目以将其添加到uri,然后使用它来获取数据.一个例子或教程会有所帮助.谢谢:)

I can't figure out how to get the selected item to add it to the uri and then use it to get data. An example or tutorial would be helpful. Thanks :)

推荐答案

我将在ViewModel中创建一个"SelectedCustomer"属性(Customers属性旁边),并将其绑定到SelectedItem.然后,在该属性的设置器上,您可以导航到所需的页面.这样,您就可以消除混乱的事件和命令.

I would create a "SelectedCustomer" property in the ViewModel (next to you Customers property) and bind it to the SelectedItem. Then, on the setter of that property you can navigate to your desired page. This way you eliminate the messy events and command.

<ListBox x:Name="state_list 
         ItemsSource="{Binding Customers}" 
         SelectedItem="{Binding SelectedCustomer, Mode=TwoWay}">

...

public Customer SelectedCustomer
{
  get
  {
    return _selectedCustomer;
  }
  set
  {
    if (value != null)
    {
    _selectedCustomer = value;
    //Navigate to your page here, either with Navigator class or any other mechanism you have in place for changing content on screen
    }
  } 

}

这篇关于使用MVVM从列表框中获取selecteditem的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆