在我的程序中,我试图从Xamarin应用程序的列表中获取当前id,以便更改等效于Id的bool。
在应用程序中,用户表示一个列表,以及与每个元素关联的开关。目标是在切换开关时将表中的bool从false更改为true。
[
在我的.cs文件中,当切换开关时更新bool(请参见底部的handle_toggled):
public partial class DefineBuilding : ContentPage
{
//string currentDefineDescription;
//int currentDefineId;
DefineTable current;
private const string Url = "http://localhost:5000/define";
private HttpClient _client = new HttpClient();
private ObservableCollection<DefineTable> _define;
public DefineBuilding(DefineTable defineList)
{
if (defineList == null) throw new ArgumentNullException();
//BindingContext = defineList;
//currentDefineId = defineList.defineId;
//currentDefineDescription = defineList.defineDescription;
current = defineList;
InitializeComponent();
//defineList = Current_item.BindingContext;
}
protected override async void OnAppearing()
{
var content = await _client.GetStringAsync(Url);
var posts = JsonConvert.DeserializeObject<IEnumerable<DefineTable>>(content);
_define = new ObservableCollection<DefineTable>(posts);
defineBuildingItems.ItemsSource = _define;
base.OnAppearing();
}
async void Handle_Toggled(object sender, Xamarin.Forms.ToggledEventArgs e)
{
//current.defineId =
current.defineBool = true;
defineDataService defineTable = new defineDataService();
await defineTable.UpdateData(current);
}
async void Handle_Clicked(object sender, System.EventArgs e)
{
await Navigation.PushAsync(new ChecklistPage());
}
}
}
然而,当处理拨动开关时,我无法获得Id。在我的xaml文件中,我能够获取Id,但是我不知道如何应用此ID。
以下是我的Xaml文件中的示例(请参阅BindingContext =“{Binding defineId}”):
<StackLayout Orientation="Horizontal">
<StackLayout Orientation="Vertical">
<Label Text="{Binding defineDescription}"
HorizontalOptions="FillAndExpand" x:Name="Current_item"/>
</StackLayout>
<Switch BindingContext ="{Binding defineId}" HorizontalOptions="EndAndExpand"
Toggled="Handle_Toggled"/>
</StackLayout>
如何在课堂上获得正确的ID?
答案 0 :(得分:1)
sender是触发事件的对象,在本例中是一个Switch。由于您已将id指定为Switch的绑定上下文,因此您应该能够通过执行适当的强制转换来检索它:
async void Handle_Toggled(object sender, Xamarin.Forms.ToggledEventArgs e)
{
var id = (int) ((Switch)sender).BindingContext;
//current.defineId =
current.defineBool = true;
defineDataService defineTable = new defineDataService();
await defineTable.UpdateData(current);
}