怎么使用MVVM light绑定windows phone控件事件到command?
怎么使用MVVM light绑定windows phone控件事件到command?
toooony
12 years, 8 months ago
Answers
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
我是悲剧哥
answered 12 years, 8 months ago