Windows Phone-怎么使用MVVM light绑定windows phone控件事件到command?

Windows Phone-怎么使用MVVM light绑定windows phone控件事件到command?

甜柠檬 发布于 2017-10-30 字数 61 浏览 1172 回复 1

怎么使用MVVM light绑定windows phone控件事件到command?

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

甜柠檬 2017-11-05 1 楼

1。首先,创建一个新的Windows手机应用程序项目,并安装“MVVM light工具包“

MVVM light 已经引用到工程中了,就像前图所描述的,现在就可以正常使用MVVM light了。

2.从window phone toolkit中添加一个Microsoft.Phone.Controls.Toolkit.dll引用,

3.加命名空间

<phone:PhoneApplicationPage
xmlns:toolkit="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Toolkit"
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
xmlns:cmd="clr-namespace:GalaSoft.MvvmLight.Command;assembly=GalaSoft.MvvmLight.Extras.WP71"
> .

4.加一个PhoneTextBox控件到xxx.xaml中,并且要设置一个ActionIcon

<StackPanel x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<toolkit:PhoneTextBox x:Name="phoneTextBox" ActionIcon="/Images/Search.png"/>
</StackPanel>

5.xxx.xaml.cs 有了一个新的ICommand属性类型"ActionIconTappedCommand",接下来加一个"OnActionIconTapped()"方法,当TextBox的action icon被点击后,将会回调这个方法。

 public partial class MainPage : PhoneApplicationPage
{
//..

public ICommand ActionIconTappedCommand
{
get;
private set;
}

private void OnActionIconTapped()
{
MessageBox.Show("Action icon tapped.");
}
}

6.添加一个新的RelayCommand(MVVM Light 类对象),并设置ActionIconTappedCommand

 public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();

this.ActionIconTappedCommand = new RelayCommand(this.OnActionIconTapped);

this.DataContext = this;
}

//..
}

7.用EventToCommand处理PhoneTextBox的ActionIconTapped事件:

 <toolkit:PhoneTextBox x:Name="phoneTextBox" ActionIcon="/Images/Search.png">
<i:Interaction.Triggers>
<i:EventTrigger EventName="ActionIconTapped">
<cmd:EventToCommand Command="{Binding ActionIconTappedCommand}" />
</i:EventTrigger>
</i:Interaction.Triggers>
</toolkit:PhoneTextBox>

参考资料:http://www.windowsphonegeek.com/articles/How-to-bind-a-Windows-Phone-control-Event-to-a-Command-using-MVVM-Light