c# - How to trigger the setter of a property of an enum when passing as parameter? -
imagine have property , private field:
private messageboxresult donotuseme_result; public messageboxresult myresult { { return donotuseme_result; } set { donotuseme_result = value; } }
messageboxresult enum used result of messagebox (wpf). nevertheless getting problems when passing myresult
methods, because automatically uses value type of enum , changed results getting collected gc
, because totally new variable specified inside scope of method (taskbasedshow
)...
my current setup:
public delegate void onresult(messageboxresult res); private messageboxresult donotuseme_result; public mainwindow() { initializecomponent(); onres += messagebox_onres; taskbasedshow("my message", "my caption", messageboxbutton.yesno, messageboximage.question, myresult); } public messageboxresult myresult { { return donotuseme_result; } set { donotuseme_result = value; onres?.invoke(value); } } public void taskbasedshow(string message, string caption, messageboxbutton buttons, messageboximage image, messageboxresult resultprop) { task.factory.startnew(() => { resultprop = messagebox.show(message, caption, buttons, image); }); } /// <summary> /// getting triggered after user pressed button. /// </summary> /// <param name="res">the pressed button.</param> private void messagebox_onres(messageboxresult res) { messagebox.show(res.tostring()); } public event onresult onres;
i have read following documentations:
- https://msdn.microsoft.com/en-us/library/sbbt4032.aspx
- https://msdn.microsoft.com/en-us/library/cc138362.aspx
but seems enum
not provide set(value)
method.
the problem:
when setting variable of property of enum (inside mothod), setter not triggered , therefore custom events.
what should do:
it should trigger onres
when setting property because setter getting triggered , therefore subscribers of onresult
event. working example:
public mainwindow() { initializecomponent(); onres += messagebox_onres; myresult = messageboxresult.cancel; }
it open messagebox displaying "cancel".
note:
one solution using property inside taskbasedshow
:
task.factory.startnew(() => { myresult = messagebox.show(message, caption, buttons, image); });
because uses reference type , not passed value type.
you should use callback result value back
public async void taskbasedshow( string message, string caption, messageboxbutton buttons, messageboximage image, action<messageboxresult> resultcallback) { var result = await task.run(() => messagebox.show(message, caption, buttons, image ) ); resultcallback( result ); }
and call like
taskbasedshow( "my message", "my caption", messageboxbutton.yesno, messageboximage.question, r => myresult = r );
Comments
Post a Comment