Отправить идентификатор динамически при нажатии кнопки xamarin - PullRequest
0 голосов
/ 27 февраля 2020

У меня есть динамически генерируемый список, показывающий номер счета и дату счета, а также кнопку «еще», которая при нажатии приведет пользователя к подробному просмотру счета.

Я изо всех сил пытается определить, как связать идентификатор, а затем отправить идентификатор после нажатия кнопки «еще».

мой код:

    <?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="App1.LoggedIn">
    <ContentPage.Content>
        <StackLayout Padding="10">
            <Label x:Name="header" FontSize="25" Text="Invoices" 
           HorizontalOptions="Center" VerticalOptions="CenterAndExpand"
            />
            <ListView x:Name="BillView" ItemsSource="{Binding Bills}">
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <ViewCell>
                            <Grid>
                                <Label YAlign="Center" XAlign="Center" Grid.Column="0" Text="{Binding InvoiceNumber}" />
                                <Label YAlign="Center" XAlign="Center" Grid.Column="1" Text="{Binding InvoiceDate}" />
                                <Button Grid.Column="2" Text="More" VerticalOptions="StartAndExpand" Clicked="GetInvoiceDetails(HELP!!)" />
                            </Grid>
                        </ViewCell>
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>
        </StackLayout>
    </ContentPage.Content>
</ContentPage>

Ответы [ 2 ]

1 голос
/ 28 февраля 2020

Если вы используете Mvvm, вы можете перенести модель по нажатию кнопки.

Вы можете использовать эту команду для ее достижения.

   <Button Grid.Column="2" Text="More" VerticalOptions="StartAndExpand" Command="{ Binding BindingContext.GetIdCommand, Source={x:Reference Name=BillView} }"  CommandParameter="{Binding .}"  />

Вот код макета.

    <StackLayout Padding="10">
        <Label x:Name="header" FontSize="25" Text="Invoices" 
       HorizontalOptions="Center" VerticalOptions="CenterAndExpand"
        />
        <ListView x:Name="BillView" ItemsSource="{Binding Bills}">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <Grid>
                        <Label YAlign="Center" x:Name="MyInvoiceNumber" XAlign="Center" Grid.Column="0" Text="{Binding InvoiceNumber}" />
                            <Label YAlign="Center" XAlign="Center" Grid.Column="1" Text="{Binding InvoiceDate}" />

                        <Button Grid.Column="2" Text="More" VerticalOptions="StartAndExpand" Command="{ Binding BindingContext.GetIdCommand, Source={x:Reference Name=BillView} }"  CommandParameter="{Binding .}"  />
                        </Grid>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
    </StackLayout>

Вот код фона макета.

 public partial class MainPage : ContentPage
{
    public MainPage()
    {
        InitializeComponent();
        BindingContext = new MyBillViewModel(Navigation);
    }
}

Вот MyBillViewModel.

  public class MyBillViewModel
{
    public ICommand GetIdCommand { protected set; get; }
    public ObservableCollection<Bill> Bills { get; set; }
    public INavigation Navigation { get; set; }

    public MyBillViewModel(INavigation navigation)
    {
        this.Navigation = navigation;
        Bills = new ObservableCollection<Bill>();
        Bills.Add(new Bill { InvoiceDate = "2020/2/23", InvoiceNumber = "1" });
        Bills.Add(new Bill { InvoiceDate = "2020/2/23", InvoiceNumber = "2" });
        Bills.Add(new Bill { InvoiceDate = "2020/2/23", InvoiceNumber = "3" });
        Bills.Add(new Bill { InvoiceDate = "2020/2/23", InvoiceNumber = "4" });
        Bills.Add(new Bill { InvoiceDate = "2020/2/23", InvoiceNumber = "5" });
        Bills.Add(new Bill { InvoiceDate = "2020/2/23", InvoiceNumber = "6" });
        Bills.Add(new Bill { InvoiceDate = "2020/2/23", InvoiceNumber = "7" });


        GetIdCommand = new Command<Bill>(async (key) => {
            Bill bill=(Bill)key;
            await Navigation.PushAsync(new Page2(bill));

        });
     }
}

Вот режим Bill.

    public class Bill
{
    public  string InvoiceNumber { get; set; }
    public string InvoiceDate { get; set; }
}

Вот мой бегущий GIF.

enter image description here

Я обновляю свое демо на github, вы можете обратиться к нему.

https://github.com/851265601/FormsListviewCommand

0 голосов
/ 27 февраля 2020

Попробуйте установить команду для вашей кнопки вместо события Clicked,

<Button Grid.Column="2" BindingContext="{Binding Source={x:Reference BillView}, Path=BindingContext}"   Command="{Binding YOUCOMMAND}"   CommandParameter="{Binding Source={x:Reference Item}, Path=BindingContext}"></Button>

А для вашей модели представления попробуйте это,

 public ICommand YOUCOMMAND
        {
            get
            {
                return new Command((e) =>
                    {
                        // Your logic
                    });
            }
        }

Поскольку вы использовали представление списка и ваши команды находятся внутри DataTemplate, привязка привязана к контексту привязки каждой отдельной модели в ItemSource.

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