代码之家  ›  专栏  ›  技术社区  ›  RationalGeek

让Silverlight MVVM使用Expression Blend设计时数据?

  •  4
  • RationalGeek  · 技术社区  · 14 年前

    我非常支持使用Silverlight的MVVM模式。目前,我通过在视图的代码后面新建ViewModel,将ViewModel连接到视图,因此:

    public partial class SomePage : UserControl
    {
        public SomePage()
        {
            InitializeComponent();
    
            // New up a ViewModel and bind to layout root
            var vm = new SomeViewModel();
            LayoutRoot.DataContext = vm;
        }
    }
    

    然后所有的绑定都在视图中处理,所有的逻辑都在ViewModel中处理,正如模式所希望的那样。

    但是,这样连接它们意味着设计器不能很好地工作,我不能使用Expression Blend设计时数据。我知道有像mvvmlight这样的库可以帮助所有这些工作,但是我不喜欢引入库,因为这是“另外一件事”。

    3 回复  |  直到 14 年前
        1
  •  3
  •   Jeremy Likness    14 年前

    有几种方法可以使用。

    弗斯特 ,让表达式的示例数据和设计时属性(即d:DataContext)在设计器中接管。在代码中,只需对视图模型绑定进行条件设置:

    if (!DesignerProperties.IsInDesignTool)
    {
       var vm = new SomeViewModel();
       LayoutRoot.DataContext = vm; 
    }
    

    第二 ,则可以使用绑定的特殊设计时视图模型:

    LayoutRoot.DataContext = DesignerProperties.IsInDesignTool ?
        new DesignViewModel() : new MyViewModel(); 
    

    最后

    // constructor
    private Widget[] _designData = new[] { new Widget("Test One"), new Widget("Test Two") };
    
    public MyViewModel()
    {
       if (DesignerProperties.IsInDesignTool)
       {
           MyCollection = new ObservableCollection<Widget>(_designData);       
       }
       else 
       {
           MyService.Completed += MyServiceCompleted;
           MyService.RequestWidgets();
       }
    }
    
    private void MyServiceCompleted(object sender, AsynchronousEventArgs ae)
    {
       // load up the collection here
    }
    

        2
  •  2
  •   Community CDub    7 年前

    你要找的是“ ". mvvmlight有ViewModelLocator的概念,我正在一个项目中使用它,并取得了很好的效果。

    这是一篇很好的文章 Roboblob http://blog.roboblob.com/2010/01/17/wiring-up-view-and-viewmodel-in-mvvm-and-silverlight-4-blendability-included/ 这篇文章有一个示例解决方案,因此它确实有助于理解。Rob改进了mvvmlight实现,我认为做得很好。

        3
  •  1
  •   Dave Swersky    14 年前

    我在设计WPF应用程序时遇到过类似的问题。我学到的一个技巧是声明一个xmlns,这样就可以在XAML中嵌入一个对象数组:

    xmlns:coll="clr-namespace:System.Collections;assembly=mscorlib"
    

    <coll:ArrayList x:Key="questions">
        <local:QuestionItem Title="FOO"></local:QuestionItem>
    </coll:ArrayList>
    

    <ListBox x:Name="lstStuff" ItemsSource="{StaticResource questions}" />