将命令添加到ListView中的单选按钮



我有一个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>

稍后,我将为一些问题添加复选框和条目。我很难用选定的答案填充我的视图模型。这可行吗?还是我应该考虑另一种方法?

您可以将RadioButton的命令直接绑定到ViewModel,这样就不需要在Model中多次定义它。

在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 

});
}