使用MVVM从列表框中获取选择项

Zie*_*asr 2 windows-phone-7 mvvm-light

我在这个项目中使用MVVM,我有一个绑定到Customers集合的列表框.我想创建一个事件来使用elementselected的id导航detailsPage:

 <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>
Run Code Online (Sandbox Code Playgroud)

我无法弄清楚如何将所选项添加到uri然后使用它来获取数据.示例或教程会很有帮助.谢谢 :)

Ale*_*nea 6

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

<ListBox x:Name="state_list 
         ItemsSource="{Binding Customers}" 
         SelectedItem="{Binding SelectedCustomer, Mode=TwoWay}">
Run Code Online (Sandbox Code Playgroud)

...

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
    }
  } 

}
Run Code Online (Sandbox Code Playgroud)

  • 并确保"SelectedItem"使用TwoWay绑定 (2认同)