绑定到UWP中的视图模型和源实体

问题描述 投票:0回答:1

[我正在使用作为UI社区工具包的一部分提供的DataGrid组件,并希望有几个显示下拉列表的单元格(ComboBox)。

下拉列表的ItemsSource应该来自视图模型,而SelectedItem应该绑定到当前项目(行)的上下文。

<tc:DataGrid ItemsSource="{Binding GridItems}">
  <tc:DataGrid.Columns>
    <tc:DataGridTemplateColumn Tag="ExampleColumn" Header="Example Column">
      <tc:DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
          <ComboBox ItemsSource="{Binding <ViewModelProperty>}" SelectedItem="{Binding <ContextProperty>}" />
        </DataTemplate>
      </tc:DataGridTemplateColumn.CellTemplate>
    </tc:DataGridTemplateColumn>
    ...
  </tc:DataGrid.Columns>
</tc:DataGrid>

[如何配置ComboBox的绑定,以便将ItemsSource从页面的视图模型中拉出,而SelectedItem绑定到GridItems集合中的当前项目。

[大多数文章都谈论使用RelativeSource和AncestorType,但我认为UWP应用程序中不提供这些功能。

c# xaml uwp uwp-xaml
1个回答
0
投票

我如何配置ComboBox的绑定,以便将ItemsSource从页面的视图模型中拉出,而SelectedItem绑定到GridItems集合中的当前项目。

ComboBox的DataContext是GridItems集合中的当前项目(例如,模型),如果您想将SelectedItem与GridItems集合中的当前项目绑定,只需将当前项目的属性与SelectedItem绑定。对于ItemsSource,如果要与页面的视图模型绑定,则可以订阅ComboBox的Loading事件,然后在此事件中将页面视图模型的列表设置为ItemsSource。例如:

。xaml:

<tc:DataGrid ItemsSource="{Binding GridItems}">
    <tc:DataGrid.Columns>
        <tc:DataGridTemplateColumn Tag="ExampleColumn" Header="Example Column">
            <tc:DataGridTemplateColumn.CellTemplate>
                <DataTemplate x:DataType="local:Model">
                    <ComboBox Loading="ComboBox_Loading" SelectedItem="{Binding MySelectedItemFromModel}"/>
                </DataTemplate>
            </tc:DataGridTemplateColumn.CellTemplate>
        </tc:DataGridTemplateColumn>
    </tc:DataGrid.Columns>
</tc:DataGrid>

。cs:

private void ComboBox_Loading(FrameworkElement sender, object args)
{
    ComboBox box = sender as ComboBox;
    box.ItemsSource = ViewModelFromPage.Lists;
}
© www.soinside.com 2019 - 2024. All rights reserved.