Note that there are some explanatory texts on larger screens.

plurals
  1. POTo pass a delegate/command as a parameter to another command in MVVM
    text
    copied!<p>I have a user control 'A' that has another user control 'B' as its child. The usecase scenario being, when the user clicks a button on 'A', it should <em>request</em> 'B' to process some information (typically relating to the state of 'B') and get the result, which will then be used in some calculation in 'A'.</p> <p>Now, I am using MVVM pattern. The viewmodel of 'A' does not have any reference to either the UI of A or B. I am exactly looking for this: When a user cliks a button on the UI of 'A', I need to call a command in 'B', by passing a delegate in the viewmodel of 'A' as a parameter to that command. This way, when the command in 'B' processes information, it can <em>then</em> call the callback function passed from 'A'.</p> <p>Now, the delegate is parameter-less. Once the command in usercontrol 'B' processes some information, it updates <em>its state</em>. This state is a dependency property which will be binded to a property in the viewmodel of 'A'.</p> <p>Is there a way to achieve something like this?</p> <p>I have a working solution currently. But I want to improvise the code and make it better. This is my current temporary workaround to this problem:</p> <p>When the user clicks a button in 'A', I am having an Event Handler in 'A' (xaml.cs). In the event handler, as I have the reference of 'B', I am checking if the command in 'B' can be executed, and then call it. Then, I check if command (in viewmodel of 'A') can be executed, and then call it.</p> <p>If my question was not descriptive enough, here is a code sample to support it:</p> <p><strong>XAML of 'A':</strong></p> <pre><code>&lt;bNameSpace:B x:Name="BObject" DepenPropertyInB="{Binding PropInA, Mode=OneWayToSource}"/&gt; .... &lt;telerik:RadButton Content="Process" HorizontalAlignment="Right" Height="30" Width="80" Grid.Column="2" Click="ProcessButton_Click" /&gt; </code></pre> <p><strong>XAML.cs of A:</strong></p> <pre><code>private void ProcessButton_Click(object sender, RoutedEventArgs e) { if (BObject.StateDataRequestedCommand.CanExecute("")) BObject.StateDataRequestedCommand.Execute(""); if(ViewModel.ProcessInfoRequestedCommand.CanExecute("")) ViewModel.ProcessInfoRequestedCommand.Execute(""); } </code></pre> <p><strong>ViewModel of A:</strong></p> <pre><code>private void OnProcessInfoRequestedCommand(string anyValue) { // read the value of PropInA and do some processing } </code></pre> <p><strong>ViewModel of B:</strong></p> <pre><code>private void OnStateDataRequestedCommand(string anyValue) { // Bases on B's state do some calc and update DepenPropertyInB } </code></pre>
 

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