【问题标题】:set Combobox ItemsSource BindingContext to ViewModel将 Combobox ItemsSource BindingContext 设置为 ViewModel
【发布时间】:2020-06-29 21:55:18
【问题描述】:

我有一个 ListView,我在其中放置了一些 ComboBox,如下所示:

<ListView x:Name="ListViewCategories" SelectedItem="{Binding SelectedCategory}"  ItemsSource="{Binding ListCategoryPart}" SelectionChanged="ListViewCategories_SelectionChanged">
    <ListView.ItemContainerStyle>
        <Style TargetType="ListViewItem">
            <Setter Property="HorizontalContentAlignment" Value="Stretch" />
        </Style>
    </ListView.ItemContainerStyle>
    <ListView.View>
        <GridView>
            <GridViewColumn Header ="{x:Static p:Resources.Machine}" >
                <GridViewColumn.CellTemplate>
                    <DataTemplate>
                        <ComboBox
                ItemsSource="{Binding ListCutMachines}"
                SelectedValuePath="ID"
                SelectedValue="{Binding DefaultCutMachine, UpdateSourceTrigger=PropertyChanged}"
                DisplayMemberPath="Name" Width="100"
                />
                    </DataTemplate>
                </GridViewColumn.CellTemplate>
            </GridViewColumn>
        </GridView>
    </ListView.View>
</ListView>

DefaultCutMachine 是我的对象 CategoryPart(ListView 中列出的项目)的一部分。

但我想要的不是从我的对象中获取 Combobox ItemsSource,而是从我的 ViewModel 中获取。

如何绑定我的所有项目组合框 ItemsSource,而不是从项目,而是从我的 ViewModel?(我阅读了“BindingContext”,但没有找到如何在 ComboBox ItemsSource 上执行此操作)

【问题讨论】:

    标签: wpf combobox binding


    【解决方案1】:

    本质上,您希望创建一个绑定,该绑定具有 RelativeSource 与您的 ViewModel 的正确 DataContext

    这是一个例子:

    ItemsSource="{Binding RelativeSource={RelativeSource AncestorType={x:Type ListView}}, Path=DataContext.ListCutMachines}"
    

    我希望这会有所帮助。

    【讨论】:

    • 太好了,效果很好,谢谢。能否请您解释一下AncestorType={x:Type ListView}} 的部分不明白它是如何工作的,谢谢
    • RelativeSource 中的 AncestorType 告诉绑定查找可视化树,并找到第一个元素是 ListView。因此,当绑定尝试解析 Path=DataContext.ListCutMachines 时,它将针对它找到的第一个 ListView 上的数据上下文对象执行此操作。我希望这是有道理的。
    猜你喜欢
    • 1970-01-01
    • 2011-09-01
    • 2016-11-27
    • 2010-12-21
    • 1970-01-01
    • 1970-01-01
    • 2016-06-07
    • 2023-04-01
    相关资源
    最近更新 更多