【问题标题】:MVVM View BindingMVVM 视图绑定
【发布时间】:2011-07-08 22:20:08
【问题描述】:

假设我有一个项目列表。所以我有 2 个视图:ListView 和 ItemView。

我还有 2 个 ViewModel:ListViewModel 和 ItemViewModel。

在 ListViewModel 中,我创建并初始化 ItemViewModels 的 ObservableCollection。 在 ListView 中,我有 ListBox 和 ItemTemplate -> ItemView,并且 ItemSource 绑定到 ListViewModel 中的 ObservableCoolection。 我想将每个 ItemView 绑定到每个 ItemViewModel,这样我就可以在 ItemView.xaml 中使用绑定,但我无法实现它。

【问题讨论】:

  • 我没看懂你的最后一句话,你能把XAML和代码贴在后面吗?

标签: silverlight mvvm binding


【解决方案1】:

我从您的问题中了解到,您希望将 ItemViewModel 绑定到 ItemView.xaml,而您的 ListBox 位于其他一些 xaml(比如 ListBox.xaml)中。您不想在 ListBox.xaml 中应用与 ItemViewmodel 和 ItemVIew 相关的绑定。如果这是问题,你 可以很容易地创建一个DataTemplate 映射来实现这样的:

<Window
    xmlns:vw="namespace of your view files (i.e. xaml files. ListBox.xaml and ItemView.xaml)"
    xmlns:ViewModels="namespace of your view model files (i.e. ItemViewModel.cs, ListBoxViewModel.cs)">
    <Window.Resources>
        <DataTemplate DataType="{x:Type ViewModels:ItemViewModel}">
                <vw:ItemView />
        </DataTemplate>
    </Window.Resources>
    <Grid>
        <ListBox ItemsSource="{Binding Path=List of ItemViewmodel in ListBoxViewModel.cs}"
    </Grid>
</Window>

然后,您的 ItemViewModel 类将与 ItemView 映射,因为它在 Resources 中指定,没有任何键。现在您可以在 ItemView.xaml 中应用绑定。看,这里不需要指定ListBox的Itemtemplate,会自动解析的。如果你想指定 ItemTemplate (并且不想在资源中指定),那么写这个:

<ListBox.ItemTemplate>
    <DataTemplate>
        <vw:ItemView />
    </DataTemplate>
</ListBox.ItemTemplate>

无论哪种方式都应该工作:)

【讨论】:

    猜你喜欢
    • 2011-01-31
    • 1970-01-01
    • 2011-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-23
    • 2018-11-25
    相关资源
    最近更新 更多