将Combobox ItemsSource BindingContext设置为ViewModel

时间:2020-03-18 18:48:29

标签: wpf combobox binding

我有一个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中列出的项目)的一部分。

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

如何从我的ViewModel而不是从Items绑定我的所有Item Comboboxes ItemsSource?(我读过“ BindingContext”,但在ComboBox ItemsSource上找不到该方法)

1 个答案:

答案 0 :(得分:1)

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

这里是一个例子:

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

我希望这会有所帮助。