Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Workaround for UpdateSourceTrigger LostFocus on Silverlight Datagrid?

I have a Silverlight 2 application that validates data OnTabSelectionChanged. Immediately I began wishing that UpdateSourceTrigger allowed more than just LostFocus because if you click the tab without tabbing off of a control the LINQ object is not updated before validation.

I worked around the issue for TextBoxes by setting focus to another control and then back OnTextChanged:

Private Sub OnTextChanged(ByVal sender As Object, ByVal e As TextChangedEventArgs)
    txtSetFocus.Focus()
    sender.Focus()
End Sub

Now I am trying to accomplish the same sort of hack within a DataGrid. My DataGrid uses DataTemplates generated at runtime for the CellTemplate and CellEditingTemplate. I tried writing the TextChanged="OnTextChanged" into the TextBox in the DataTemplate, but it is not triggered.

Anyone have any ideas?

like image 849
Dave Lowther Avatar asked Oct 31 '08 14:10

Dave Lowther


1 Answers

You can do it with a behavior applied to the textbox too

// xmlns:int is System.Windows.Interactivity from System.Windows.Interactivity.DLL)
// xmlns:behavior is your namespace for the class below
<TextBox Text="{Binding Description,Mode=TwoWay,UpdateSourceTrigger=Explicit}">
    <int:Interaction.Behaviors>
       <behavior:TextBoxUpdatesTextBindingOnPropertyChanged />
    </int:Interaction.Behaviors>
</TextBox>


public class TextBoxUpdatesTextBindingOnPropertyChanged : Behavior<TextBox>
{
    protected override void OnAttached()
    {
        base.OnAttached();

        AssociatedObject.TextChanged += new TextChangedEventHandler(TextBox_TextChanged);
    }

    protected override void OnDetaching()
    {
        base.OnDetaching();

        AssociatedObject.TextChanged -= TextBox_TextChanged;
    }

    void TextBox_TextChanged(object sender, TextChangedEventArgs e)
    {
        var bindingExpression = AssociatedObject.GetBindingExpression(TextBox.TextProperty);
        bindingExpression.UpdateSource();
    }
}
like image 168
Simon_Weaver Avatar answered Nov 10 '22 05:11

Simon_Weaver