0

在我的应用程序中,我在页面中有一个数据上下文,但是,我想将此数据上下文移动到 ListView,因为我需要创建更多数据上下文。

我试图分配一个名称来调用 DataContext 网格,但不起作用......

<Page
x:Class="Food_UsuarioWin8.Pages.HUB"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:Food_UsuarioWin8.Pages"
xmlns:vmSegments="using:Food_UsuarioWin8.ViewModels"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">

 </Page.Resources>
<Page.DataContext>
    <vmSegments:ViewModelSegments x:Name="DataContextSegments"/>
</Page.DataContext>

 <ListView x:Name="ListViewSegments" Grid.Row="1" Margin="0" DataContext="{StaticResource DataContextSegments}" ItemContainerStyle="{StaticResource ListViewSItemtyleECFood}" >
  <Viewbox>
  </Viewbox>
 </ListView>
4

1 回答 1

0

There are two ways you can create a "composite" data context.

My preference is a single ViewModel class with properties for each data context you need:

public class ViewModel
{
    public ViewModel()
    {
        Segments = new ViewModelSegments();
        SomethingElse = new ViewModelSomethingElse();
    }

    public ViewModelSegments Segments { get; set; }
    public ViewModelSomethingElse SomethingElse { get; set; }
}

In XAML you set your main ViewModel as DataContext for the page and then bind individual controls to its properties:

<ListView ItemsSource="{Binding Segments}" />

Alternatively you can put individual data context classes into resources and use them from there:

<Page.Resources>
    <vm:ViewModelSegments x:Key="DataContextSegments" />
    <vm:ViewModelSomethingElse x:Key="DataContextSomethingElse" />
</Page.Resources>

<ListView DataContext="{StaticResource DataContextSegments}" ItemsSource="{Binding}" />
于 2013-01-30T06:11:54.920 回答