AWG Blogs

Sunday, September 9, 2012

Use Explicit Binding to Force Update on TextChanged

If you have a TextBox inside a DataTemplate in a DataGrid, and want any TextChanged event to update the binding, set Mode=TwoWay, UpdateSourceTrigger=Explicit on the binding or else you will get an error:
"Operation is not valid due to the current state of the object."

More Notes:

Since this is an Explicit binding, you will need to hook to the event using a behavior such as Prism's UpdateTextBindingOnPropertyChanged. But since that has been made obsolete in Silverlight 5 you will need to get the class itself from the Prism code and add it to your project manually and then attach that like so:
                        <data:DataGridTemplateColumn.CellEditingTemplate>
                            <DataTemplate>
                                <TextBox Height="23" HorizontalAlignment="Left"  
Name="textBox1" VerticalAlignment="Top" Width="120" 
                 
Text="{Binding Invmprop, Mode=TwoWay}" >

                                    <i:Interaction.Behaviors>
                                        <local:MyUpdateTextBindingOnPropertyChanged />
                                    </i:Interaction.Behaviors>
                                </TextBox>
                            </DataTemplate>
                        </data:DataGridTemplateColumn.CellEditingTemplate>
Why is it obsolete? Because Silverlight 5 introduced UpdateSourceTrigger=PropertyChanged, which works fine in uncontained textboxes but not when they are in DataGrids (or so I've observed), so for those in DataGrids, I had to perform the above workaround.

No comments:

Post a Comment