【问题标题】:How to pass bound data item to a ListBox item's ViewModel?如何将绑定数据项传递给 ListBox 项的 ViewModel?
【发布时间】:2010-08-09 18:38:36
【问题描述】:

尝试使用 mvvm-light 解决一个非常简单的问题,但是经过几天的 StackOverflow 筛选和大量 Google 搜索后,我没有想出一个简单的解决方案。

我有一个带有 dataTemplate 的 ListBox。 dataTemplate 包含一个 userControl 来显示内容

<ListBox ItemSource={Binding Posts} >
    <ListBox.ItemTemplate>
        <DataTemplate>
            <ctl:PostControl/>  <-- child control I'm trying to pass data to
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

我在父页面(用于绑定帖子,没有问题)和 PostControl 上都有 viewModels 来显示各个帖子。

问题:如何将单个帖子(来自帖子控件的绑定)放入 PostControl 的 viewModel 中?

我在 PostControl 定义上使用了 DataContext:

DataContext="{Binding PostControlViewModel, Source={StaticResource Locator}}"

这似乎可行,但我需要访问由父 ListBox 绑定到此控件的单个 Post。如何将单个帖子传递到 PostControls 的视图模型中?

【问题讨论】:

    标签: silverlight mvvm-light


    【解决方案1】:

    如果没有看到您的 UserCtl,很难说出了什么问题,但我会说您的 ListBox 看起来不错,并且每个 Control 都应该绑定到 Posts 的一个元素。

    你应该做的是在UserCtl中覆盖它,所以我认为DataContext="..."属性应该简单地去。

    假设 Posts 是 PostControlViewModel 的列表。如果是(Business)Model Post 类的列表,则需要转换器。但它应该包含 ViewModel。

    【讨论】:

    • 我想到了 ViewModel 列表(恕我直言,这很笨拙,但它会起作用),但转换器是一个有趣的想法,谢谢!
    • @Mekon:如果它对你有用,那么好的。但我仍然认为 ViewNodel 应该公开 ViewModel 列表,而不是 Biz 对象列表。
    猜你喜欢
    • 2019-04-08
    • 1970-01-01
    • 2015-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多