答案是:MVVM。不要在代码隐藏中使用事件注册,而是在 ViewModel 中调用命令。首先,不是绑定到 Data 对象,而是绑定到 ViewModel(或者如果您在列表中,则绑定到表示单个列表项的 ViewModel)。然后,不要使用 Click 事件,而是让您的 ViewModel 公开一个可以直接在数据绑定 VM 上调用的命令。
这是我的联合国新闻OSS WP7 应用程序中的一个简化示例:( XAML , C# )
<DataTemplate x:Key="ArticleItemDataTemplate">
<StackPanel>
<toolkit:ContextMenuService.ContextMenu>
<toolkit:ContextMenu>
<toolkit:MenuItem Command="{Binding NavigateToArticle}" Header="read article"/>
<toolkit:MenuItem Command="{Binding ShareViaEmail}" Header="share via email"/>
<toolkit:MenuItem Command="{Binding ShareOnFacebook}" Header="share on facebook"/>
<toolkit:MenuItem Command="{Binding ShareOnTwitter}" Header="share on twitter"/>
</toolkit:ContextMenu>
</toolkit:ContextMenuService.ContextMenu>
<TextBlockText="{Binding Title}">
</StackPanel>
</DataTemplate>
public ICommand ShareOnTwitter
{
get
{
return new RelayCommand(() =>
IoC.Get<ISocialShareService>().ShareOnTwitter(ShareableOnSocialNetwroks));
}
}
public ICommand ShareOnFacebook
{
get
{
return new RelayCommand(() =>
IoC.Get<ISocialShareService>().ShareOnFacebook(ShareableOnSocialNetwroks));
}
}
public ICommand ShareViaEmail
{
get
{
return new RelayCommand(() =>
IoC.Get<ISocialShareService>().ShareViaEmail(ShareableOnSocialNetwroks));
}
}
这是我的Neurons WP7 OSS 项目中使用的相同想法的另一个简化示例:( XAML,C#)
<DataTemplate x:Key="YouTubeVideoItem">
<Grid>
<Button >
<toolkit:ContextMenuService.ContextMenu>
<toolkit:ContextMenu IsZoomEnabled="False">
<toolkit:MenuItem Command="{Binding NavigateToVideo}" Header="play video" />
<toolkit:MenuItem Command="{Binding ViewInBrowser}" Header="open in browser" />
<toolkit:MenuItem Command="{Binding SendInEmail}" Header="share via email" />
<toolkit:MenuItem Command="{Binding FacebookInBrowser}" Header="share on facebook" />
<toolkit:MenuItem Command="{Binding TweetInBrowser}" Header="share on twitter" />
</toolkit:ContextMenu>
</toolkit:ContextMenuService.ContextMenu>
<Custom:Interaction.Triggers>
<Custom:EventTrigger EventName="Click">
<GalaSoft_MvvmLight_Command:EventToCommand Command="{Binding NavigateToVideo}"/>
</Custom:EventTrigger>
</Custom:Interaction.Triggers>
<StackPanel Orientation="Horizontal">
<Image Height="90" Source="{Binding ImageUrl}" />
<TextBlock Width="271" Text="{Binding Title}" />
</StackPanel>
</Button>
</Grid>
</DataTemplate>
public ICommand ViewInBrowser
{
get
{
return new RelayCommand(() =>
TaskInvoker.OpenWebBrowser(this.ExternalLink.OriginalString)
);
}
}
public ICommand TweetInBrowser
{
get
{
return new RelayCommand(() =>
IoC.Get<IMessenger>().Send(new NavigateToMessage(PageSources.WebBrowser, TwitterUri)));
}
}
public ICommand FacebookInBrowser
{
get
{
return new RelayCommand(() =>
IoC.Get<IMessenger>().Send(new NavigateToMessage(PageSources.WebBrowser, FacebookUri)));
}
}