Добавление команды в radiobutton в ListView

#xamarin.forms

#xamarin.forms

Вопрос:

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

ViewModel определяет «TheQuestions» как:

 TheQuestions = new ObservableCollection<Question>();
TheQuestions.Add(new Question
{
  Id = 123,
  Attribute1 = Value1,
  TheQuestion = "Blah blah?",
  Answer = false,
});
  

ListView выглядит следующим образом:

 <ListView ItemsSource="{Binding TheQuestions, Mode=TwoWay}">
  <ListView.ItemTemplate>
    <DataTemplate>
      <ViewCell>
        <StackLayout>
          <Label Text="{Binding TheQuestion}" />
          <StackLayout Orientation="Horizontal">
            <RadioButton Command="{ ?? }"  CommandParameter="{Binding .}"  GroupName="{Binding Id,Mode=TwoWay}" Text="Yes" TextColor="Green" />
            <RadioButton Command="{Binding ??}" GroupName="{Binding Id, Mode=TwoWay}" Text="No" TextColor="Red" />
        </StackLayout>
      </StackLayout>
    </ViewCell>
   </DataTemplate>
  </ListView.ItemTemplate>
</ListView>
  

Позже я добавлю флажки и записи, а также к ряду вопросов. Я испытываю трудности, когда дело доходит до заполнения моей viewmodel выбранным ответом. Это выполнимо или мне следует рассмотреть другой подход?

Комментарии:

1. почему бы вам просто не привязать IsChecked к вашей виртуальной машине?

2. Хороший вопрос, я спустился в кроличью нору и не думал о таком простом решении.

Ответ №1:

Вы могли бы привязать команду RadioButton непосредственно к ViewModel, чтобы вам не нужно было определять ее в модели несколько раз.

в 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:local="clr-namespace:App32"
             x:Class="App32.MainPage"
             
             x:Name="Page" // set name of ContentPage
             
             >
  
 <RadioButton Command="{Binding Source={x:Reference Page}, Path=BindingContext.RadioCommand}"  CommandParameter="{Binding .}"  GroupName="{Binding Id,Mode=TwoWay}" Text="Yes" TextColor="Green" />
            <RadioButton Command="{Binding Source={x:Reference Page}, Path=BindingContext.RadioCommand}" CommandParameter="{Binding .}" GroupName="{Binding Id, Mode=TwoWay}" Text="No" TextColor="Red" />
  

В вашей ViewModel

 public ICommand RadioCommand { get; set; }
  
 public xxxViewModel()
{
   TheQuestions = new ObservableCollection<Question>();
   TheQuestions.Add(new Question
   {
    Id = 123,
    Attribute1 = Value1,
    TheQuestion = "Blah blah?",
    Answer = false,
   });

   RadioCommand = new Command((obj)=> {

                var model = obj as Question;

                var answer = model.Answer;

                //do something you want 



            });

}