Изменение объекта за ListView, при нажатии кнопки - PullRequest
0 голосов
/ 02 марта 2020

У меня есть довольно простое приложение, в котором он будет заполнять модуль spesifi c объектами, которые называются: Вопрос. Этот объект имеет атрибуты publi c, такие как: String question {get; set;} и ​​int selectedAnswer {get; set;}.

Чего я хотел бы добиться, так это то, что когда пользователь нажимает eather YesButton или NoButton -button, это изменяет selectedAnswer внутри указанного объекта c на 0-2. В этом случае, если пользователь нажимает Нет, это значение внутри этого объекта изменится на 1, если Да, оно превратится в 2. По умолчанию 0.

Как я могу сослаться на этот объект, на Clicked- обработчик события? Вот страница XML:

 <ContentPage.Content>

        <ListView ItemsSource="{Binding Modules}"
                  x:Name="QuestionsList_module"

                      HasUnevenRows="True"
                      Margin="10,10" >

            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <StackLayout Margin="10, 20, 0, 10" >

                            <Label Text="{Binding name}"/>

                            <ListView ItemsSource="{Binding questionList}"
                                      x:Name="Item"
                                      HasUnevenRows="True"
                                      Margin="30,30">

                                <ListView.ItemTemplate>
                                    <DataTemplate>
                                        <ViewCell>

                                            <StackLayout Padding="0,10,0,10">
                                                <Label Text="{Binding question}"></Label>

                                                <Grid HorizontalOptions="Center" Padding="0,20,0,10">
                                                    <Grid.ColumnDefinitions >

                                                        <ColumnDefinition Width="*" />
                                                        <ColumnDefinition Width="*" />

                                                    </Grid.ColumnDefinitions>

                                                    <Button Margin="0,0,20,0" x:Name="YesButton" Text="YES" FontAttributes="Bold" BorderColor="LightGreen"  BorderWidth="5" CornerRadius="20" Clicked="YesButton_Clicked" />

                                                    <Button Margin="0,0,20,0" Grid.Column="1" x:Name="NoButton" Text="NO" FontAttributes="Bold" BorderColor="HotPink"  BorderWidth="5" CornerRadius="20" />

                                                </Grid>
                                            </StackLayout>
                                        </ViewCell>
                                    </DataTemplate>
                                </ListView.ItemTemplate>
                            </ListView>
                        </StackLayout>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>

        </ListView>
    </ContentPage.Content> 

А вот моя пока попытка получить информацию внутри отправителя:

private void YesButton_Clicked(Object sender, EventArgs e)
        {

            var button = (Button)sender;

            Grid listview = (Grid)button.Parent;
            StackLayout ss = (StackLayout)listview.Parent;


        }

И вот так я могу получить верхняя метка, но по-прежнему не получает «доступа» к самому объекту.

Обратите внимание, что все модули имеют тип: ObservableCollection, а все объекты Question также находятся в ObservableCollection, и окончательная модель будет выглядеть следующим образом:

new Module{
name = "this is the name of this module",
description = "Here goes the description",
isVisible = false,
ModuleIsChecked = false,
questionList = "And here's the list of those questions in ObservableCollection -list"}

1 Ответ

1 голос
/ 02 марта 2020

используйте BindingContext кнопки, чтобы получить связанный объект, затем приведите его к правильному типу

var button = (Button)sender;

// cast to the appropriate class
var item = (Question)button.BindingContext;
...