【问题标题】:Bind ListPicker in MVVM (Selection_Changed)在 MVVM 中绑定 ListPicker (Selection_Changed)
【发布时间】:2014-07-02 16:21:52
【问题描述】:

我正在尝试将命令附加到 ListPicker 的事件 Selection_Changed

我的 xaml 中有以下列表选择器代码:

   <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 只是我的 ViewModel 中的一个字符串列表,我怎样才能创建一个简单的 Commad 例如,它只会在 ListPicker 中显示一个带有当前选定字符串的 MessageBox ?

类似于我在后面的代码中写的这个函数:

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

编辑:

我刚刚创建了这个简单的函数:

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

通过了:

PickerCommand = new RelayCommand<SelectionChangedEventArgs>(Test);

但我有错误说我传递的参数无效,这是为什么呢?

【问题讨论】:

  • 您不需要使用该语法将控件绑定到事件。你只需要:SelectionChanged="PickerCommand"
  • 但是如何在视图模型中编写这样的命令?
  • 在您的 VM 中创建一个名为 SelectedSentence 的属性,将其绑定到 SelectedItem。你可以在你的虚拟机中检查它,然后在你的命令中采取相应的行动。完成。
  • 你能写一个代码吗?我仍然不知道该怎么做我是 mvvm 的新手
  • 对不起 - 我的错误,应该读两遍 - 这是你想要的一个例子:social.technet.microsoft.com/wiki/contents/articles/…

标签: c# xaml windows-phone-8 mvvm windows-phone


【解决方案1】:

你需要这样做:

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

然后

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

使用 MVVM Light,它有一些帮助它的类。

【讨论】:

  • 谢谢你的回答,我要放什么而不是''而不是'ActionForPickerCommand'我只是放了一个'public void function',它只显示一个MessageBox,但我得到一个错误以及如何使用 RelayCommand 在 ViewModel 中获取 ListPicker 的选定元素?谢谢!
  • object应该是发送的对象的类型,不确定是不是SelectionChangedEventArgs,
  • 对于 selectItem,您需要创建一个将绑定到选择器 SelectItem - TwoWays 的属性!!!
  • 我编辑了我最初的问题,你能告诉我为什么我传递的函数无效吗?
猜你喜欢
  • 1970-01-01
  • 2014-12-31
  • 2015-03-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多