【发布时间】:2021-12-26 13:49:20
【问题描述】:
大家好,抱歉我的英语不好。
我正在 Xamarin Forms 上开发应用程序,但遇到了 event invocation 的问题。
我有一个带有各种标签的 ContentView 和两个用于编辑和删除相关对象的按钮。如您所见,我尝试了各种事件调用方法,但EventHandler 在我调用它时始终为空。
InstrumentCard.xaml.cs 代码:
public partial class InstrumentCard : ContentView
{
public event EventHandler<InstrumentEventArgs> DeleteClicked;
public event EventHandler<InstrumentEventArgs> EditClicked;
private Instrument _i;
public InstrumentCard(Instrument i)
{
InitializeComponent();
_i = i;
lblID.Text = i.ID.ToString();
lblName.Text = i.Nome;
lblQty.Text = $"Quantità: {i.Qty.ToString()}";
}
public Instrument GetInstrument()
{
return _i;
}
private void btnEdit_Clicked(object sender, EventArgs e)
{
RaiseEdit(new InstrumentEventArgs { Instrument = _i});
}
private void RaiseEdit(InstrumentEventArgs args)
{
EditClicked?.Invoke(this, args);
}
private void btnDelete_Clicked(object sender, EventArgs e)
{
DeleteClicked?.Invoke(this, new InstrumentEventArgs
{
Instrument = _i
});
}
}
MainPage.xaml.cs 代码:
public partial class MainPage : ContentPage
{
List<Instrument> instruments = new List<Instrument>();
public MainPage()
{
InitializeComponent();
}
protected override async void OnAppearing()
{
base.OnAppearing();
Reload();
}
public async void Reload()
{
List<Instrument> instruments = await App.Database.GetInstrumentsAsync();
lblCounter.Text = $"Ci sono {instruments.Count} strumenti";
if (instruments.Count == 0)
{
stcNoData.IsVisible = true;
stcData.IsVisible = false;
stcDock.IsVisible = false;
}
else
{
stcNoData.IsVisible = false;
stcData.IsVisible = true;
stcDock.IsVisible = true;
stcInstruments.Children.Clear();
instruments.ForEach(instr =>
{
InstrumentCard ic = new InstrumentCard(instr);
ic.DeleteClicked += Ic_DeleteClicked;
ic.EditClicked += Ic_EditClicked;
stcInstruments.Children.Add(new InstrumentCard(instr));
});
}
}
private void Ic_EditClicked(object sender, InstrumentEventArgs e)
{
Navigation.PushAsync(new AddInstrument(e.Instrument));
}
private void Ic_DeleteClicked(object sender, InstrumentEventArgs e)
{
stcInstruments.Children.Remove(sender as InstrumentCard);
App.Database.DeleteInstrumentAsync(e.Instrument);
Reload();
}
}
我不知道出了什么问题。 谢谢你的帮助
【问题讨论】:
-
如果没有订阅者,则事件为空。
-
表示没有人订阅这个事件。您是否订阅了 EditClicked += ..... 之类的地方?
-
是的,订阅在 MainPage.xaml 中,但正如您在屏幕截图中看到的那样,流程在之前停止。我尝试在 WPF 中复制相同的代码,它在那里工作正常。
-
显示包括 xaml 在内的其余代码
-
好的,我修改了答案
标签: c# xamarin xamarin.forms event-handling