简体   繁体   English

在MVVM中绑定ListPicker(Selection_Changed)

[英]Bind ListPicker in MVVM (Selection_Changed)

I am trying to attach a command to the event Selection_Changed of the ListPicker 我正在尝试将命令附加到ListPicker的事件Selection_Changed

I have the following code for the listpicker in my xaml : 我的xaml中有以下用于listpicker的代码:

   <toolkit:ListPicker 
         x:name="picker" ItemsSource="{Binding Sentences}"    
         SelectionChanged="{Binding PickerCommand, Mode=TwoWay}" >
            <toolkit:ListPicker.ItemTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding }"/>
                </DataTemplate>
            </toolkit:ListPicker.ItemTemplate>
        </toolkit:ListPicker>

Sentences is just a list of string in my ViewModel, how can I create a simple Commad for example that will just show a MessageBox with the current selected string in the ListPicker ? 句子只是ViewModel中的字符串列表,如何创建一个简单的Commad例如,它将仅在ListPicker中显示带有当前选定字符串的MessageBox?

Something similar to this function that i wrote in the code Behind : 我在代码Behind中编写的与此函数相似的东西:

private void PickerCommand(object sender, SelectionChangedEventArgs e)
{
    if (piker.SelectedItem != null) 
    {
      MessageBox.Show(piker.SelectedItem.ToString());
    }
}

EDIT : 编辑:

I just created this simple function : 我刚刚创建了这个简单的函数:

public void Test()
{
MessageBox.Show("Test!");
}

passed it : 通过了:

PickerCommand = new RelayCommand<SelectionChangedEventArgs>(Test);

But I have the error saying that the argument that I passed is invalid, why is that ? 但是我有一个错误,说我传递的参数无效,为什么呢?

You need to do this: 您需要这样做:

<toolkit:ListPicker x:name="picker" ItemsSource="{Binding Sentences}">
 <i:Interaction.Triggers>
    <i:EventTrigger EventName="SelectionChanged">
        <command:EventToCommand Command="{Binding PickerCommand, Mode=OneWay}" />
    </i:EventTrigger>
</i:Interaction.Triggers>
        <toolkit:ListPicker.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding }"/>
            </DataTemplate>
        </toolkit:ListPicker.ItemTemplate>

and then 接着

    public class MYViewModel :ViewModelBase
{
   public MyViewModel()
   {
       PickerCommand = new RelayCommand<object>(ActionForPickerCommand);
    }
    public ICommand PickerCommand {get;set;}
}

Use MVVM Light, that has some classes that help in it. 使用MVVM Light,它提供了一些帮助。

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

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