[英]How to set a x:Name to a control in a CollectionView / ListView in Xamarin.Forms
我正在嘗試為 xaml 中的 ImageButton 命名,但它不起作用,因為它位於 CollectionView 中,有人知道如何為控件命名嗎?
我正在嘗試做的事情:
列表中的每個項目都有一個心形按鈕,我希望能夠點擊心形按鈕來保存該項目,給它一個小動畫,我想給 ImageButton 一個名字,並在后面的代碼中用它做一些事情。
感謝您的幫助
因為 CollectionView 是循環的,所以如果在 ImageButton 中定義 x:name 是錯誤的。
根據你的描述,我寫了一個小例子供你參考。 它在 xaml 中創建了一個CollectionView ,里面有一個ImageButton 。
單擊ImageButton 時,該行的 ImageButton 和 Lable 信息會發生變化。
這是 xaml 代碼(創建了一個包含 ImageButton 和 Label 的 CollectionView):
<StackLayout>
<CollectionView x:Name="mytest">
<CollectionView.ItemTemplate>
<DataTemplate>
<StackLayout Orientation="Horizontal">
<Label Text="{Binding .}"></Label>
<ImageButton Clicked="ImageButton_Clicked" Source="xxx.jpg" HeightRequest="50" WidthRequest="50"></ImageButton>
</StackLayout>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
</StackLayout>
這是cs代碼:
public partial class MainPage : ContentPage
{
ObservableCollection<string> observableCollection = new ObservableCollection<string>();
public MainPage()
{
InitializeComponent();
//Simulation data
observableCollection.Add("aaa");
observableCollection.Add("bbb");
observableCollection.Add("ccc");
mytest.ItemsSource = observableCollection;
}
private void ImageButton_Clicked(object sender, EventArgs e)
{
(((sender as ImageButton).Parent as StackLayout).Children[0] as Label).Text = "Clicked and modified";
(((sender as ImageButton).Parent as StackLayout).Children[1] as ImageButton).Source = "xxx1.jpg";
}
}
在ImageButton_Clicked方法中,使用(sender as ImageButton).Parent
獲取上層視圖,然后使用.Children[x]
獲取StackLayout內部的所有信息並進行修改。
這是屏幕截圖:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.