【发布时间】:2014-09-22 14:21:43
【问题描述】:
我有一个带有按钮的自定义 ViewCell。当我单击此按钮时,我想在显示 ListView 和 ViewCells 的 ContentPage 中处理此单击。在 iOS 中,我会使用来自 Cell 的代表来执行此操作。我将如何在 C#/Xamarin.Forms 中执行此操作?
这是我的自定义 ViewCell:
public CustomCell ()
{
button = new Button ();
button.Text = "Add";
button.VerticalOptions = LayoutOptions.Center;
button.Clicked += [WHAT DO DO HERE???];
var nameLabel = new Label ();
nameLabel.SetBinding (Label.TextProperty, "name");
nameLabel.HorizontalOptions = LayoutOptions.FillAndExpand;
nameLabel.VerticalOptions = LayoutOptions.Center;
var viewLayout = new StackLayout () {
Padding = new Thickness (10, 0, 10, 0),
Orientation = StackOrientation.Horizontal,
Children = { nameLabel, button }
};
View = viewLayout;
}
我的 ContentPage 使用它作为 ViewCell 看起来像这样:
ListView.ItemTemplate = new DataTemplate (typeof(CustomCell));
那么,我如何捕捉按钮按下?
请询问您是否需要澄清。
好的,所以我至少知道了:
这是我的内容页面:
...
ListView.ItemTemplate = new DataTemplate (() => new CustomCell (CustomCellButtonClicked));
}
void CustomCellButtonClicked (CustomCell m, EventArgs e)
{
//How do I get my associated object here?!
System.Diagnostics.Debug.WriteLine ("Pressed cell " + m.ToString ());
}
这是我的牢房:
public EventArgs e = null;
public event ButtonClickEvent ClickListener;
public delegate void ButtonClickEvent (AddCardCell m, EventArgs e);
public CustomCell (ButtonClickEvent Listener)
{
ClickListener += Listener;
customButton = new Button ();
customButton.Text = "Add";
customButton.VerticalOptions = LayoutOptions.Center;
customButton.Clicked += AddButtonClicked;
...
}
void AddButtonClicked (object sender, EventArgs e)
{
if (ClickListener != null) {
ClickListener (this, e);
}
}
所以,现在剩下的就是获取与单元格关联的实际对象。在 ListView 的 ItemSelected 中,是这样完成的:
ListView.ItemSelected += async (object sender, SelectedItemChangedEventArgs e) => {
var obj = (HSObject)e.SelectedItem;
};
我该怎么做?
知道了!这可能不是一个好的解决方案,但它似乎有效:
void CustomCellButtonClicked (CustomCell m, EventArgs e)
{
var myObject = m.BindingContext;
}
我会接受唯一的答案,因为它把我推向了正确的方向。 (而且这可能是一种更好的方法)。
【问题讨论】:
-
我也在寻找解决方案,环顾四周似乎是不可能的。基本单元格对象无法访问页面对象,因此无法访问某些事件,例如操作表和导航。你想处理什么事件?
标签: c# xamarin xamarin.forms