Rob
Rob

Reputation: 1708

Passing state information from view to viewmodel

What is the best approach to pass the current view model state - specifically what textbox has focus - back to the view model?

My requirement is for context specific search, depending what text box has focus determines what field to search on in the database.

I'm using the MVVM pattern and really don't want to put any code in the view.

Upvotes: 3

Views: 214

Answers (4)

Gene C
Gene C

Reputation: 2030

You could use the InvokeCommandAction available in the Expression Blend SDK:

    <StackPanel>
    <TextBox>
        <i:Interaction.Triggers>
            <i:EventTrigger EventName="GotFocus">
                <i:InvokeCommandAction Command="{Binding YourCommand}"/>
            </i:EventTrigger>
        </i:Interaction.Triggers>
    </TextBox>
    </StackPanel>

Where:

xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"

Upvotes: 1

Wallstreet Programmer
Wallstreet Programmer

Reputation: 9677

You don't want to put view related stuff in your VM. Focus is clearly view related stuff. In the VM you should keep track of the currently selected search field in some bindable property. Changing focus in the view should update the current property somehow. I don't see a problem with code behind in the view, which would be the easiest way of keeping track of focus and updating the VM. If you don't want to do code behind, then this can also be done by value converters or attached behavior.

Upvotes: 1

Dean Chalk
Dean Chalk

Reputation: 20451

create an attached property for the TextBox which is an IsFocussed property. Then use 2 way binding to your ViewModel

Upvotes: 2

Jakub
Jakub

Reputation: 534

I don't really see a way of doing this without slightly violating the View-ViewModel contract (ie. the ViewModel is View agnostic). You can use System.Windows.Input's Keyboard.FocusedElement and then get that element's data binding to perform your search within your search command in your ViewModel.

Upvotes: 0

Related Questions