实例化ViewModel(需要简单的帮助)

时间:2012-03-05 16:37:45

标签: wpf mvvm

MVVM的新手,它点击到位,但我似乎有知识/概念差距...

我的MainWindow显示项目列表:

<Window.DataContext>
    <vm:MainWindowViewModel />
</Window.DataContext>

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
        <RowDefinition Height="*" />
        <RowDefinition Height="100" />
    </Grid.RowDefinitions>

    <vw:HeaderView Grid.Row="0" />

    <vw:RegistersView Grid.Row="1" />

    <vw:LogView Grid.Row="2" />
</Grid>

MainWindowViewModel创建主数据存储库。

RegistersView具有对象的ListView(以及其他内容),并负责编辑值。我可以通过公开ObservableCollection&lt;&gt;来将数据放入RegistersView中的ListView中。并将上面的行改为

<vw:RegistersView DataContext="{Binding PropertyNameOfCollectionForListView}" Grid.Row="1" />

看起来MVVM(更不用说显而易见)也为RegistersView创建一个ViewModel ......但是我缺乏对如何以非常基本的方式连接它的洞察力。我知道我可以使用Unity,Prism和所有其他人使用IOC / DI但是......我吗?我真正想要的是能够公开Registers-View特定属性以与模型交互并定义要绑定的命令等。

我觉得我想说

<vw:RegistersView viewmodel="RegistersViewModel(PropertyNameOfCollectionForListView)" />

有人可以指出我正确的方向吗 - 我已阅读,阅读和阅读,但我错过了。

感谢您的耐心等待; - &gt;

2 个答案:

答案 0 :(得分:0)

您的MainWindowViewModel可以公开RegistersViewModel类型的属性,然后您可以将其绑定到XAML中的RegisterView.DataContext,如下所示:

<vw:RegistersView Grid.Row="1" 
                  DataContext="{Binding RegistersViewModelPropertyName}" />

显然RegistersViewModelPropertyName应该引用已经实例化的RegistersViewModel。这取决于你如何做到这一点,无论是在MainViewModel构建阶段还是实施RegistersViewModelPropertyName getter都是懒惰的。

答案 1 :(得分:0)

  

似乎非常MVVM(更不用说显而易见)也创建了一个ViewModel   对于RegistersView

我完全同意,这感觉非常像MVVM。所以目前您的MainWindowViewModel如下所示:

class MainWindowViewModel
{
  public ObservableCollection<RegisterViewModel> PropertyNameOfCollectionForListView {get; set;}
}

为什么不创建一个视图模型来封装与UI一起公开的项目集合及其命令。因此,新视图模型可能如下所示:

public class RegistersViewModel
{
  public ObservableCollection<RegisterViewModel> RegisterViewModelCollection {get; set;}

  public ICommand AddRegister { get; set; }

  public ICommand RemoveRegister { get; set; }
}

即。它仍然暴露了原始集合,但现在添加了与此集合相关的命令。

您的MainWindowViewModel现在公开了这种新的视图模型:

class MainWindowViewModel
{
  public RegistersViewModel RegistersViewModelProperty {get; set;}
}

然后将usercontrol绑定到此属性:

在此用户控件的XAML中绑定到列表和命令

<UserControl x:Class="RegistersView" ... >
   <ListView ItemsSource={Binding Path=RegisterViewModelCollection}/>
   <Button Content="Add" Command="{Binding Path=AddRegister}"/>
</UserControl>

不,这不需要任何DI或IoC!

相关问题