我有一个相当简单的应用程序,它将在该特殊模块中填充名为“问题”的对象。该对象具有公共属性,例如:字符串问题{get; set;},然后int selectedAnswer {get;设置;}。
我想要实现的是,当用户按下eather YesButton或NoButton -button时,会将特定对象内的selectedAnswer更改为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-object也在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"}
使用按钮的BindingContext
获取绑定的对象,然后将其强制转换为正确的类型
var button = (Button)sender;
// cast to the appropriate class
var item = (Question)button.BindingContext;