Wednesday, December 8, 2010

WPF, MVVM and TextBoxes

Overall, I like WPF and MVVM.  That’s not to say that I think MVVM is a perfect design pattern.  I find myself breaking the purity of MVVM sometimes because I think there’s a lot of compromise needed to do what I want to without adding complexity.

Anyway, one of the biggest gripes about MVVM and TextBoxes is that the data for bound TextBoxes is updated when the TextBox control loses focus.  But that makes sense, right?  Well, what if you’ve updated a TextBox and hit a MenuItem to save your data.  Guess what?  The TextBox doesn’t lose focus and your save takes the stale TextBox data.  Needless to say this is VERY frustrating…

One solution would be to move the focus off of the TextBox like so:

((System.Windows.UIElement)System.Windows.Input.Keyboard.FocusedElement).MoveFocus(new System.Windows.Input.TraversalRequest(System.Windows.Input.FocusNavigationDirection.Next));

You can call that before you actually execute your save command, but even that seems like a bit too much effort to do what should logically be done anyway… I’ve done the above in some of my projects, but there has to be some other way to do what I want…

Instead of using the vanilla Menu control, I turned to Infragistics’ xamMenu.  I was hoping that their menu would take into account something like the issue I was having with my TextBox data.  I was right… sort of.  It turns out that if I use their xamMenu like so:

<ig:xamMenu>
<ig:xamMenuItem Header="Save">
<ig:XamMenuItem.InputBindings>
<MouseBinding MouseAction="LeftClick" Command="{Binding SaveCommand}"/>
</ig:XamMenuItem.InputBindings>
</ig:xamMenuItem>
</ig:xamMenu>

The above doesn’t do what I want either… After some experimenting, I found that if I use the vanilla MenuItem elements instead of Infragistics’ XamMenuItem elements, my TextBox data updates and saves.  It seems weird to me that using a combination of the Infragistics xamMenu and the vanilla MenuItem causes the data to update correctly, yet using all Infragistics’ elements doesn’t.

<shrug> In the end I ended up using vanilla Button elements in the xamMenu because using the vanilla MenuItem elements caused spacing issues:

<ig:xamMenu>    
<Button Command="{Binding SaveCommand}" Background="Transparent" BorderBrush="Transparent">
<StackPanel Orientation="Horizontal">
<Image Stretch="None" Source="{StaticResource Image}"/>
<TextBlock Background="Transparent" Margin="4,0,0,0" Text="Save"/>
</StackPanel>
</Button>
</ig:xamMenu>

No comments: