Navigation.PushAsyn c не работает внутри пользовательского элемента управления в формах Xamarin - PullRequest
0 голосов
/ 13 июля 2020

У меня есть ListView на моей ContentPage. Внутри ListView.ItemTemplate у меня есть пользовательский контроль. В пользовательском элементе управления есть кнопки изображения. При нажатии кнопки ImageButton я хочу переместить другую страницу, но она не работает. Код запускается без ошибок, но ничего не произошло. Тот же код PushAsyn c работает со всеми другими страницами содержимого, но не в пользовательском элементе управления. Пожалуйста, помогите мне в этом отношении, что мне делать.

Код ListView внутри ContentPage:

<ListView x:Name="lvPosts" HasUnevenRows="True" SeparatorVisibility="None" 
IsVisible="False">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <Grid Padding="10">
                            <controls:CardView/>
                        </Grid>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>

UserControl CardView:

<Frame  xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         xmlns:d="http://xamarin.com/schemas/2014/forms/design"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"       
         mc:Ignorable="d"
         xmlns:local="clr-namespace:MyApp.General"
         VerticalOptions="Start"         
         x:Class="MyApp.Controls.CardView">

<Frame.Content>
    <Grid Padding="10" >
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="100" />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*" />
            <ColumnDefinition Width="*" />
            <ColumnDefinition Width="*" />
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>
        
        <Label                              
            Grid.Column="0" 
            Grid.ColumnSpan="4"
            Grid.Row="0"                    
            Text="{Binding Title}"                     
            HorizontalOptions="FillAndExpand"
            TextColor="#479774"
            FontSize="Medium" 
            Style="{StaticResource DefaultFontStyle}"
            Opacity="0.8">
        </Label>
        <StackLayout Orientation="Vertical" Grid.Row="1" Grid.Column="0">
            <ImageButton
                x:Name="imgPdf"
                Source="pdf.png"                    
                Aspect="AspectFill"
                Clicked="imgPdf_Clicked"/>
        </StackLayout>
        <StackLayout Orientation="Vertical" Grid.Row="1" Grid.Column="1">
            <ImageButton 
                x:Name="imgContent"
                Source="document2.png"
                Aspect="AspectFill"
                Clicked="imgContent_Clicked"/>
        </StackLayout>
        <StackLayout Orientation="Vertical" Grid.Row="1" Grid.Column="2">
            <ImageButton
                x:Name="imgSummary"
                Source="document.png"
                Aspect="AspectFill"
                Clicked="imgSummary_Clicked"/>
        </StackLayout>
        <StackLayout Orientation="Vertical" Grid.Row="1" Grid.Column="3">
            <ImageButton
                x:Name="imgVideo"
                Source="video1.png"
                Aspect="AspectFill"
                Clicked="imgVideo_Clicked"/>
        </StackLayout>            
    </Grid>
</Frame.Content>
</Frame>    

И код на ImageButton:

    private async void imgVideo_Clicked(object sender, EventArgs e)
    {
        Post post = this.BindingContext as Post;
        await Navigation.PushAsync(new WebViewPage(post));
    }

1 Ответ

0 голосов
/ 13 июля 2020

Мы могли вызвать метод Navigation.PushAsync только в ContentPage . В вашем случае CardView является подклассом Frame, поэтому он никогда не будет работать.

Лучшее решение - вызвать метод в Code Behind (ViewModel или ContentPage). Поскольку вы использовали Custom View. Было бы лучше обрабатывать logi c с помощью привязки данных.

Если вы действительно хотите вызвать метод в CardView, вы можете определить свойство в App и передать текущая навигация из ContentPage.

в App.xaml.cs

public INavigation navigation { get; set; }

в ContentPage

Примечание. Вам необходимо вызвать следующие строки в каждой ContentPage.

public xxxContentPage()
{
   InitializeComponent();

   var app = App.Current as App;
   app.navigation = this.Navigation;
}

в CardView

var app = App.Current as App;

var navigation = app.navigation;

navigation.PushAsync(xxx);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...