【问题标题】:How to alter a DataTemplate based on a property on the page ViewModel in Windows Phone 7?如何根据 Windows Phone 7 中 ViewModel 页面上的属性更改 DataTemplate?
【发布时间】:2013-02-11 04:17:57
【问题描述】:

我有一个 ViewModel,它包含一个布尔属性,它告诉您用户是否已通过身份验证。

我有一个 WrapPanel,它绑定到一组配置文件。这些配置文件的 DataTemplate 有一个图标 - 用户未通过身份验证时的闭合挂锁和用户通过身份验证时打开的挂锁。理想情况下,这些将绑定到 ViewModel 上的布尔值,但模板的 DataContext 是单独的配置文件对象。

我试过了,

  • 将绑定中的Source 选择器设置为specified here,尽管Windows Phone 7 似乎不支持x:Reference
  • 我也尝试了Inversion of Control(?) method detailed here(但在我的对象上找不到containerLocator
  • 我尝试应用 Style.Trigger,但 Windows Phone 7 不支持这些
  • 我还尝试访问后面代码中的 XAML 元素并以编程方式更新事件触发器,但是我无法处理 DataTemplate 中的 Image 元素

【问题讨论】:

    标签: windows-phone-7 xaml binding


    【解决方案1】:

    评论后编辑:WP7 不支持样式触发器。但是,如果有人在以下版本中寻找这个答案,我会在下面回复:

    我会使用Style Trigger (如here 所示)来即时更新图标Source 属性 - 作为DataTemplate 样式的一部分,这样您就可以获得Image

    【讨论】:

    • 啊,好吧,我的错,不知道。
    【解决方案2】:

    我发现一种基于an answer by Damian Antonowicz但没有实现他使用的完全反转控制方法的方法如下,

    在视图模型命名空间下创建一个解析为视图模型实例的部分类,例如

    public partial class ViewModelInstanceLocator
    {
        public AppViewModel AppViewModel // Or whatever the type of your view-model is ...
        {
            get 
            { 
                return App.VM; // Or wherever your view model instance is ...
            }
        }
    }
    

    将 XAML 页面中的另一半类定义为资源,以便可以将其称为静态资源,我在 App.xaml 中这样做了,以便可以在任何地方引用它,

    <ResourceDictionary>
        <viewmodel:ViewModelInstanceLocator x:Key="ViewModelInstanceLocator" />
        ...
    </ResourceDictionary>
    

    如果还没有对您的视图模型命名空间的引用,您可能需要包含相关的命名空间,例如在顶部,

        xmlns:viewmodel="clr-namespace:MyAppNamespace.ViewModel"
    

    最后绑定到view-model如下,

    {Binding AppViewModel.SomeProperty, Source={StaticResource ViewModelInstanceLocator}}
    

    绑定像往常一样更新,就像通过 DataContext 引用了视图模型实例一样。但是,它不适用于设计时数据

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-29
      • 1970-01-01
      • 2015-03-28
      相关资源
      最近更新 更多