【问题标题】:UWP Bind CurrentStateChanged of VisualStateGroup to ViewModelUWP 将 VisualStateGroup 的 CurrentStateChanged 绑定到 ViewModel
【发布时间】:2016-01-02 20:42:33
【问题描述】:

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

在示例中,CurrentStateChanged 事件绑定到一些代码隐藏函数

MainPage.xaml

<VisualStateGroup x:Name="AdaptiveStates" CurrentStateChanged="AdaptiveStates_CurrentStateChanged">

MainPage.xaml.cs

private void AdaptiveStates_CurrentStateChanged(object sender, VisualStateChangedEventArgs e)

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

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

MainPage.xaml

<VisualStateGroup x:Name="AdaptiveStates" CurrentStateChanged="{Binding AdaptiveStates_OnCurrentStateChanged}">

MainPageViewModel.cs

public ICommand AdaptiveStates_OnCurrentStateChanged
{
   get { throw new NotImplementedException(); }
}

DataContext 在代码隐藏文件中设置。

我得到以下编译错误:

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

这并没有真正告诉我任何关于什么是错误的信息。任何人都知道为什么会出现此错误或我如何实现我的目标?

【问题讨论】:

    标签: c# xaml mvvm uwp


    【解决方案1】:

    我通过 x:Bind 找到了我的解决方案。

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

    MainPage.xaml.cs

    public MainPageViewModel MainPageViewModel { get; set; }
    

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

    MainPageViewModel.cs

    public VisualStateChangedEventHandler AdaptiveStates_OnCurrentStateChanged
    

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

    MainPage.xaml

        <VisualStateGroup x:Name="AdaptiveStates" CurrentStateChanged="{x:Bind MainPageViewModel.AdaptiveStatesOnCurrentStateChanged}">
    

    我可能花了太多时间来弄清楚这一点。我希望这至少可以帮助遇到同样问题的其他人。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-06
      • 2019-02-03
      • 2019-01-21
      • 2017-02-11
      • 2018-06-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多