首页 > 解决方案 > 具有不同 ViewModel 的同一视图上的 Xamarin 多个绑定上下文

问题描述

我有一个ContentPage有 2 个不同的 ViewModel ( RssFornecedores, RssProdutos) 并且我在将它们绑定在一起时遇到了问题,ContentPage 我试图做这样的事情:

多个 BindingContext 在同一个 ContentPage 上,两个不同的视图?

但由于以下错误,它不起作用:

类型“viewModels:RssProdutos”用作标记扩展,但不是从 MarkupExtension 派生的

如果我添加为StaticResource BindingContext="{Binding Produto, Source = {StaticResource viewModels:RssProdutos}}"我得到错误:

未找到关键静态视图模型的静态资源:RssProdutos'

Documentos.xaml:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" 
             xmlns:viewModels="clr-namespace:AppQ4evo.ViewModels" 
             xmlns:controls="clr-namespace:AppQ4evo.CSS"
             x:Class="AppQ4evo.Views.Documentos"           
             BackgroundColor="White">

    <ContentPage.BindingContext>
        <viewModels:RssTerceiros />
    </ContentPage.BindingContext>

    <!--Common Styles Starts-->
    <ContentPage.Resources>
        <ResourceDictionary>

            <Color x:Key="LightGreenColor">#2FA999</Color>
            <Color x:Key="BorderColor">#D8D8D8</Color>

            <Style x:Key="LableStyle" TargetType="Label">
                <Setter Property="TextColor" Value="#666666" />
                <Setter Property="FontSize" Value="Large" />
            </Style>
            <Style x:Key="FrameStyle" TargetType="Frame">
                <Setter Property="HasShadow" Value="False" />
                <Setter Property="Padding" Value="0" />
                <Setter Property="CornerRadius" Value="5" />
                <Setter Property="BorderColor" Value="{StaticResource BorderColor}" />
            </Style>
            <Style x:Key="EntryStyle" TargetType="Entry">
                <Setter Property="HeightRequest" Value="40"></Setter>
                <Setter Property="Margin" Value="5,0,0,0"></Setter>
            </Style>
        </ResourceDictionary>
    </ContentPage.Resources>
    <!--Common Styles Ends-->

    <ContentPage.ToolbarItems>
        <ToolbarItem x:Name="iconAttach" Text="Documentos" Order="Primary" Icon="attach.png" Priority="-1" Clicked="Button_Clicked_AnexosAsync" />
    </ContentPage.ToolbarItems>

    <NavigationPage.TitleView>
        <StackLayout Orientation="Horizontal" VerticalOptions="Center" HorizontalOptions="Center">
            <Label Text="Documentos" FontSize="18" FontAttributes="Bold" TextColor="White" VerticalTextAlignment="Center" />
        </StackLayout>
    </NavigationPage.TitleView>

    <ContentPage.Content>
        <AbsoluteLayout Padding="0" VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand">
            <StackLayout>
                <Grid x:Name="docs" Padding="-2">
                    <Grid.RowDefinitions>
                        <RowDefinition Height="Auto"/>
                        <RowDefinition Height="Auto"/>
                        <RowDefinition Height="Auto"/>
                        <RowDefinition Height="Auto"/>
                    </Grid.RowDefinitions>

                    <StackLayout Grid.Row="0" Margin="10,20">
                        <Grid>
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="360" />
                                <ColumnDefinition Width="*" />
                            </Grid.ColumnDefinitions>
                            <Frame Style="{StaticResource FrameStyle}">
                                <controls:CustomEntry x:Name="DataDocEntry" Grid.Column="0" Text="{Binding Date, StringFormat='{0:MMMM dd, yyyy}', Source={x:Reference MainDatePicker}}" IsEnabled="false" Style="{StaticResource EntryStyle}" />
                            </Frame>
                            <DatePicker x:Name="MainDatePicker" Grid.Column="1" MinimumDate="1/1/2018" MaximumDate="12/31/2030" HeightRequest="30" BackgroundColor="Gray" Opacity="0"  />
                            <Image VerticalOptions="Center" Grid.Column="1" HorizontalOptions="End" Source="icalendar.png" HeightRequest="30" WidthRequest="30">
                                <Image.GestureRecognizers>
                                    <TapGestureRecognizer Tapped="Calendario_Clicked" NumberOfTapsRequired="1" />
                                </Image.GestureRecognizers>
                            </Image>
                        </Grid>
                        <Frame Style="{StaticResource FrameStyle}">
                            <controls:CustomEntry x:Name="NumExternoEntry" Placeholder="Número Externo" Keyboard="Numeric" />
                        </Frame>
                        <Frame Style="{StaticResource FrameStyle}">
                            <controls:CustomPicker x:Name="FornecedorEntry" Title="Selecionar Fornecedor"  />
                        </Frame>
                    </StackLayout>

                    <StackLayout Grid.Row="1" Margin="0,-10">
                        <Button x:Name="btnAdd" Text="Adicionar" Clicked="btnAddPopup_Clicked" />
                    </StackLayout>

                    <Grid x:Name="ListViewHeaders" Grid.Row="2" Margin="0,20,0,0">
                        <Grid.RowDefinitions>
                            <RowDefinition Height="40"/>
                            <RowDefinition Height="Auto"/>
                        </Grid.RowDefinitions>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="*"/>
                            <ColumnDefinition Width="60" />
                            <ColumnDefinition Width="65" />
                            <ColumnDefinition Width="80" />
                            <ColumnDefinition Width="25" />
                            <ColumnDefinition Width="60" />
                        </Grid.ColumnDefinitions>
                        <BoxView Color="Black" Grid.Row="0" Grid.ColumnSpan="8" HeightRequest="0.5" />
                        <BoxView Color="DimGray" Grid.Row="0" Grid.ColumnSpan="8" />
                        <Label Grid.Column="1" Text="Produto" XAlign="Center" YAlign="Center" TextColor="White" FontAttributes="Bold" FontSize="Small"/>
                        <Label Grid.Column="2" Text="Descrição" XAlign="Center" YAlign="Center" TextColor="White" FontAttributes="Bold" FontSize="Small"/>
                        <Label Grid.Column="3" Text="Observação" XAlign="Center" YAlign="Center" TextColor="White" FontAttributes="Bold" FontSize="Small"/>
                        <Label Grid.Column="4" Text="Qtd" XAlign="Center" YAlign="Center" TextColor="White" FontAttributes="Bold" FontSize="Small"/>
                        <Label Grid.Column="5" Text="Valor Unitário" XAlign="Center" YAlign="Center" TextColor="White" FontAttributes="Bold" FontSize="Small"/>
                        <Label Grid.Column="6" Text="IVA" XAlign="Center" YAlign="Center" TextColor="White" FontAttributes="Bold" FontSize="Small"/>
                    </Grid>
                    <ListView x:Name="DocumentsList" ItemsSource="{Binding DocumentsList, Source = {viewModels:RssProdutos}}" Grid.Row="2" HasUnevenRows="True" Margin="0,60" BackgroundColor="White">
                        <ListView.ItemTemplate>
                            <DataTemplate>
                                <ViewCell>
                                    <ViewCell.View>
                                        <Grid>
                                            <Grid.RowDefinitions>
                                                <RowDefinition Height="30"></RowDefinition>
                                            </Grid.RowDefinitions>
                                            <Grid.ColumnDefinitions>
                                                <ColumnDefinition Width="30"></ColumnDefinition>
                                                <ColumnDefinition Width="50"></ColumnDefinition>
                                                <ColumnDefinition Width="70"></ColumnDefinition>
                                                <ColumnDefinition Width="80"></ColumnDefinition>
                                                <ColumnDefinition Width="30"></ColumnDefinition>
                                                <ColumnDefinition Width="50"></ColumnDefinition>
                                                <ColumnDefinition Width="45"></ColumnDefinition>
                                            </Grid.ColumnDefinitions>
                                            <Label x:Name="ProdutoLabel" Grid.Row="0" Grid.Column="1" BindingContext="{Binding Produto, Source = {viewModels:RssProdutos}}" Text="{Binding Produto}" XAlign="Center" YAlign="Center" TextColor="Black" FontAttributes="Bold"/>
                                            <!--<Label Grid.Row="0" Grid.Column="2" Text="{Binding Descricao}" XAlign="Center" YAlign="Center" TextColor="Black" FontAttributes="Bold"/>
                                            <Label Grid.Row="0" Grid.Column="3" Text="{Binding Observacao}" XAlign="Center" YAlign="Center" TextColor="Black" FontAttributes="Bold"/>
                                            <Label Grid.Row="0" Grid.Column="4" Text="{Binding Quantidade}" XAlign="Center" YAlign="Center" TextColor="Black" FontAttributes="Bold"/>
                                            <Label Grid.Row="0" Grid.Column="5" Text="{Binding ValorUnitario}" XAlign="Center" YAlign="Center" TextColor="Black" FontAttributes="Bold"/>
                                            <Label Grid.Row="0" Grid.Column="6" Text="{Binding Iva}" XAlign="Center" YAlign="Center" TextColor="Black" FontAttributes="Bold"/>-->
                                        </Grid>
                                    </ViewCell.View>
                                </ViewCell>
                            </DataTemplate>
                        </ListView.ItemTemplate>
                    </ListView>
                </Grid>
            </StackLayout>
            <ContentView x:Name="popupAddDocumentView" Margin="40,120" Padding="10,0" IsVisible="false">
                <StackLayout VerticalOptions="Center" HorizontalOptions="Center">
                    <StackLayout Orientation="Vertical" HeightRequest="400" WidthRequest="300" BackgroundColor="Gray">
                        <Image HorizontalOptions="End" Source="close.png" HeightRequest="20" WidthRequest="20">
                            <Image.GestureRecognizers>
                                <TapGestureRecognizer Tapped="OnImageNameTapped_ClosePopup" NumberOfTapsRequired="1" />
                            </Image.GestureRecognizers>
                        </Image>
                        <Entry x:Name="ProdutoEntry" Margin="20,0,20,0" Placeholder="Produto" />
                        <Entry x:Name="DescricaoEntry" Margin="20,0,20,0" Placeholder="Descrição" />
                        <Entry x:Name="ObservacaoEntry" Margin="20,0,20,0" Placeholder="Observação" />
                        <Entry x:Name="QuantidadeEntry" Margin="20,0,20,0" Placeholder="Quantidade" />
                        <Entry x:Name="ValorUnitarioEntry" Margin="20,0,20,0" Placeholder="Valor" />
                        <Entry x:Name="IvaEntry" Margin="20,0,20,0" Placeholder="IVA" />
                        <Button x:Name="btnAddDocument" Margin="20,0,20,0" Clicked="btnAddDocument_Clicked" Text="Adicionar" />
                    </StackLayout>
                </StackLayout>
            </ContentView>
        </AbsoluteLayout>
    </ContentPage.Content>
</ContentPage> 

此致

标签: xamlxamarinxamarin.formsdata-binding

解决方案


  • 如果您的代码中还没有它的实例,则需要RssProdutos通过给它一个键来在您的 xaml 中创建一个作为资源的实例:
<ContentPage.Resources>
     <viewModels:RssProdutos x:Key="RssProdutos "/>
</ContentPage.Resources>
...
<ListView x:Name="DocumentsList" ItemsSource="{Binding DocumentsList, Source={StaticResource RssProdutos}}"
          Grid.Row="2" HasUnevenRows="True" Margin="0,60" BackgroundColor="White">
  • 如果您的代码隐藏(属性)中已经有一个实例RssProdutos,则无需添加另一个作为静态资源,您可以绑定到它:
RssProdutos RssProdutosVm {get; set;} = new RssProdutos();
<ContentPage x:Name="thispage" 
...
>
...
<ListView x:Name="DocumentsList" ItemsSource="{Binding DocumentsList, Source={Binding Source={x:Reference thispage}, Path=RssProdutosVm}}"
          Grid.Row="2" HasUnevenRows="True" Margin="0,60" BackgroundColor="White">

推荐阅读