首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >UWP将CurrentStateChanged of VisualStateGroup绑定到ViewModel

UWP将CurrentStateChanged of VisualStateGroup绑定到ViewModel
EN

Stack Overflow用户
提问于 2016-01-02 20:42:33
回答 1查看 727关注 0票数 0

我正在尝试将主/详细示例从Microsoft转换为MVVM。(样本:https://github.com/Microsoft/Windows-universal-samples/tree/master/Samples/XamlMasterDetail)

在示例中,CurrentStateChanged事件绑定到函数后面的代码

MainPage.xaml

代码语言:javascript
复制
<VisualStateGroup x:Name="AdaptiveStates" CurrentStateChanged="AdaptiveStates_CurrentStateChanged">

MainPage.xaml.cs

代码语言:javascript
复制
private void AdaptiveStates_CurrentStateChanged(object sender, VisualStateChangedEventArgs e)

如何将其绑定到视图模型?

当我试图将它绑定到这样的属性时:

MainPage.xaml

代码语言:javascript
复制
<VisualStateGroup x:Name="AdaptiveStates" CurrentStateChanged="{Binding AdaptiveStates_OnCurrentStateChanged}">

MainPageViewModel.cs

代码语言:javascript
复制
public ICommand AdaptiveStates_OnCurrentStateChanged
{
   get { throw new NotImplementedException(); }
}

DataContext在文件后面的代码中设置。

我得到以下编译错误:

\Microsoft.Windows.UI.Xaml.Common.targets(263,5):Xaml内部错误WMC9999:对象引用未设置为对象的实例。

这并不能真正告诉我什么是不对的。有谁知道为什么会出现这个错误,或者我怎样才能实现我的目标?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-01-04 12:03:28

我用x:Bind找到我的解决方案。

第一步:在代码后面将ViewModel声明为属性

MainPage.xaml.cs

代码语言:javascript
复制
public MainPageViewModel MainPageViewModel { get; set; }

第二步:将AdaptiveStates_OnCurrentStateChanged的方法返回类型为预期的VisualStateChangedEventHandler

MainPageViewModel.cs

代码语言:javascript
复制
public VisualStateChangedEventHandler AdaptiveStates_OnCurrentStateChanged

第三步:用x:Bind绑定函数

MainPage.xaml

代码语言:javascript
复制
    <VisualStateGroup x:Name="AdaptiveStates" CurrentStateChanged="{x:Bind MainPageViewModel.AdaptiveStatesOnCurrentStateChanged}">

我可能花了太多时间弄明白这点。我希望这至少能帮助那些陷入同样问题的人。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34570541

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档