大家好,很抱歉我的英語不好。
我正在 Xamarin Forms 上開發應用程式,但遇到了event invocation.
我有一個帶有各種標簽的 ContentView 和兩個按鈕來編輯和洗掉有問題的物件。如您所見,我嘗試了各種事件呼叫方法,但是在EventHandler呼叫它時始終為 null。
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();
}
}
當我除錯該方法時...

我不知道出了什么問題。感謝您的幫助
uj5u.com熱心網友回復:
問題就在這里
instruments.ForEach(instr =>
{
//here you create your instrument card
InstrumentCard ic = new InstrumentCard(instr);
ic.DeleteClicked = Ic_DeleteClicked;
ic.EditClicked = Ic_EditClicked;
//here you should use it but instead you create another one
stcInstruments.Children.Add(new InstrumentCard(instr));
});
只需將您創建的實體添加到您訂閱事件的StackPanel(我希望它是StackPanel)
stcInstruments.Children.Add(ic);
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/361473.html
標籤:C# 沙马林 xamarin.forms 事件处理
