我正在尝试使用界面处理对话框按钮。我在安卓中得到了这个解决方案 - java:
1) 声明一个接口:
public interface DialogPopUpListener {
void onConfirmButtonClick();
void onCancelButtonClick();
}
2)已实现的对话框:
public static void genericCreatePopUp(final Context context, final SimpleDialogPopUpListener listener) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Title");
builder.setMessage("Message");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// do nothing to ignore autoclose
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// do nothing to ignore autoclose
}
});
final AlertDialog dialog = builder.create();
dialog.show();
//Overriding the handler immediately after show POSITIVE
dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
listener.onConfirmButtonClick("");
dialog.dismiss();
}
});
//Overriding the handler immediately after show NEGATIVE
dialog.getButton(AlertDialog.BUTTON_NEGATIVE).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
listener.onCancelButtonClick();
dialog.dismiss();
}
});
}
3)调用函数显示对话框:
GenericPopUpDialogSimple.genericCreatePopUp(context, new SimpleDialogPopUpListener() {
@Override
public void onConfirmButtonClick(String editTxtInput) {
//handle positive button
}
@Override
public void onCancelButtonClick() {
//handle negative buton
}
});
现在我想在 C# 中迁移这个函数:
1)声明相同的接口;
2)已实现对话框创建:
public async void createDialog( SimpleDialogPopUpListener listener) {
var dialog = new MessageDialog("Message", "Title");
// Add positive command and set callback
dialog.Commands.Add(new UICommand(btnOkTxt, UICommandInvokedHandler => {
listener.onConfirmButtonClick();
}) { Id = 0 });
// Add negative command and set callback
dialog.Commands.Add(new UICommand(btnCancelTxt, UICommandInvokedHandler => {
listener.onCancelButtonClick();
}) { Id = 1 });
// Show the message dialog
await dialog.ShowAsync();
}
3)问题是,如何调用此方法并覆盖接口方法?
在 C# 中有点不同,因为它不支持像 Java 那样的内联类。一种解决方案是定义一个实现接口的类,并在调用方法时将该类用作参数。因此,您将拥有:
public class MyImplementor : DialogPopUpListener {
public void onConfirmButtonClick() {
Debug.WriteLine("T E S T --> ok");
}
public void onCancelButtonClick() {
Debug.WriteLine("T E S T --> cancel");
}
}
你调用你的方法:
createDialog(new MyImplementor());