Note that there are some explanatory texts on larger screens.

plurals
  1. POSubscribe weakly to events obtained by reflection
    primarykey
    data
    text
    <p>I'm making a <code>MessageBox</code> control in WPF using the MVVM pattern. This <code>MessageBox</code> will be used in multiple applications with different appearances, so ideally I want to keep code out of code-behind.</p> <p>I'm trying to make the <code>MessageBox</code> appear when an event is raised, specified in the declaration of the <code>MessageBox</code>.</p> <p>For example, this would be specified in the XAML of the window in which the <code>MessageBox</code> should appear.</p> <pre><code>&lt;dialog:MessageBox ShowOnEvent="EventRaised" EventContext="{Binding}" Message="I am a message box" IconType="Warning" ButtonsType="YesNo" /&gt; </code></pre> <p>The way this currently works: in the <code>MessageBox</code> ViewModel I'm using reflection to get the <code>EventInfo</code> for the event, then subscribing directly:</p> <pre><code>if (eventContext != null &amp;&amp; showOnEvent != string.Empty) { EventInfo eventInfo = eventContext.GetType ().GetEvent (showOnEvent); if (eventInfo != null) { eventInfo.AddEventHandler (eventContext, eventHandler); } else { Debug.WriteLine (string.Format ("Dialog: Couldn't find event {0} on {1}, check event name.", showOnEvent, eventContext)); } } </code></pre> <p>This shows the <code>MessageBox</code> when the event is raised, as expected.</p> <p><strong>However</strong>, the event handler means that the <code>MessageBox</code> ViewModel is not GC'd when the main window's View is disposed. This means that if another view for the main window is created, another <code>MessageBox</code> is created, so if the event is raised, both <code>MessageBox</code>s will show.</p> <p>I tried getting around this by using a <code>WeakEventManager</code>, but the <a href="http://msdn.microsoft.com/en-us/library/aa970850.aspx" rel="nofollow">Weak Event Patterns documentation</a> specify that an implementation of <code>WeakEventManager</code> should only handle one event - which means that I can't make a <code>ShowOnEventEventManager</code> with the event name as a string property and subscribe using that.</p> <p>Does anyone have any ideas for the best way to go about this?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload