我需要一些方法来根据它的ID找到视图/对象。我听说过FindViewById函数,但它不在我的ContentPage类中。我在哪里可以找到它?
上下文:我有一个内部有按钮的ListView。我不知道有多少个按钮。当用户单击其中一个按钮时,我会获得它的ID并全局存储。我想要完成的是找到这个特定的按钮,它的id存储在变量中。
<StackLayout x:Name="chooseObjectButtons">
<ListView x:Name="SlotsList" ItemsSource="{Binding .}" >
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<ViewCell.View>
<StackLayout>
<Button Text="{Binding Text}" BackgroundColor="Gray" Clicked="SlotChosen" />
</StackLayout>
</ViewCell.View>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>发布于 2016-06-11 01:32:57
将XAML更改为:
<ListView ItemsSource="{Binding Slots}" >
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<ViewCell.View>
<StackLayout>
<Button Text="{Binding Title}" BackgroundColor="Gray" Clicked="Handle_Clicked" Command="{Binding Select}" />
</StackLayout>
</ViewCell.View>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView> 手柄点击:
private Button LastButtonClicked;
void Handle_Clicked(object sender, System.EventArgs e)
{
if (LastButtonClicked != null)
{
// Change background here
}
LastButtonClicked = (Button)sender;
// Do stuff here.
}要处理每个按钮的特定命令,请使用:
public List<SlotsButtons> Slots
{
get
{
return new List<SlotsButtons>
{
new SlotsButtons
{
Title = "T1",
Select = new Command(()=>{
// do stuff here when clicked.
})
},
new SlotsButtons
{
Title = "T2",
Select = new Command(()=>{
// do stuff here when clicked.
})
}
};
}
}备注:初始问题答案。
在Xamarin形式中,类ContentPage是一个Partial class。一部分是从XAML自动生成的,另一部分代表代码。XAML生成的Partial class包含按名称查找视图的代码。
正确的名称是FindByName,您不需要在分部类中使用它,因为它已经在生成的分部类中生成了。
如果您想在代码中访问视图,只需在XAML中为其命名即可。下面是一个XAML示例:
<Button x:Name="button" ></Button>在你的代码中,你可以这样做:
button.BorderWidth = 3;如果出于某种原因,您仍然需要查找视图,请执行以下操作:
var button = this.FindByName<Button>("button");https://stackoverflow.com/questions/37754011
复制相似问题