简体   繁体   中英

How to determine which View executed a command

I have a View called InformationView.xaml and this same View is re-used to display the same information from 3 different sources (each view has a different window title). Each View has their datacontext set the same instance of one ViewModel type. Within my ViewModel class, I have an ICommand property that the 'Close' button inside the View is bound to. -- Is there a way to determine who the sender was of the command? (specifically, by window title).

Here is an example:

I have a view class with the following button ("Note: each View will have a different window title / display data from a different source--but the same View is used)

<Button Width="75" Height="23" Margin="0,0,5,5" Content="Close" Command="{Binding CloseCommand}" />

I have a ViewModel class with the following command

    public ICommand CloseCommand
    {
        get
        {
            if (this._closeCommand == null)
            {
                this._closeCommand = new RelayCommand(Command => this.OnClose());
            }     
            return _closeCommand;
        }
    }

I am looking for a way to determine which window executed the command (I will have multiple instances of the View using the same ViewModel).

I'm not sure if I understand you correctly. However, you could possibly implement the Unloaded event. Set a breakpoint inside that event method and when you hit the breakpoint. You could check the window title property for that view.

What about just making the Close() method public so that other objects can specify what the close behavior should be?

Something along the lines of this in your InformationViewModel :

public event EventHandler RequestClose;

void OnRequestClose()
{
    EventHandler handler = this.RequestClose;
    if (handler != null)
        handler(this, EventArgs.Empty);
}

Then you can use it from within your other view models like this:

InformationViewModel.Close += CloseMethod;

public CloseMethod(object sender, EventArgs e)
{
    // Implement close logic here
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM