1

I have a form with a textbox, a checkbox and a button. TextBox and Button are bound to an xml file via an XmlDataProvider defined in the Grid.Datacontext. The Text of the textbox.Text is changed on button click.

Here comes the problem: when i check/uncheck the checkbox the TextBox.Text property resets to the value from the XmlDataProvider.

How can i prevent the checkbox box from reloading the data from my DataProvider? Why does my checkbox behave this way?

This behavior also applies for other controls like ComboBox, DataPicker and RadioButton

Screenshot of demo application, code below

I created a simply example to illustrate the problem:

MainWindow.xaml:

<Window x:Class="submitbehavior.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="150" Width="250">
    <Grid>
        <Grid.DataContext>
            <XmlDataProvider x:Name="DataProvider" XPath="/" Source="datacontext.xml"/>
        </Grid.DataContext>
        <StackPanel>
            <TextBox Name="MyTextBox" Text="{Binding XPath=/Contact/Lastname}" Width="100" Height="30" VerticalAlignment="Top" HorizontalAlignment="Left"/>
            <CheckBox IsChecked="{Binding XPath=/Contact/@ShowsInterest}" Width="100" Height="30" VerticalAlignment="Top" HorizontalAlignment="Left" VerticalContentAlignment="Center" />
            <Button Content="Click" Click="ButtonBase_OnClick" Height="30" />
        </StackPanel>
    </Grid>
</Window>

MainWindow.xaml.cs

using System.Windows;

namespace submitbehavior
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
        {
            this.MyTextBox.Text = "test";
        }
    }
}

Datasource (datecontext.xml):

<Contact ShowsInterest="true">
  <Name>John</Name>
  <Lastname>Doe</Lastname>
</Contact>
Joel
  • 4,862
  • 7
  • 46
  • 71

1 Answers1

0

TextBox Text property binding will update the binding source on lost focus. Update your binding to:

    <TextBox Name="MyTextBox" Text="{Binding XPath=/Contact/Lastname, UpdateSourceTrigger=PropertyChanged}" Width="100" Height="30" VerticalAlignment="Top" HorizontalAlignment="Left"/>
adnan
  • 121
  • 5
  • 1
    UpdateSourceTrigger=PropertyChanged did the trick, however i don't agree with your explanation. Clicking a button or another textbox triggers also the lost focus event of the currently selected textbox. Anyway thank you for your help and welcome to Stackoverflow. – Joel Apr 10 '13 at 08:43
  • 1
    My explanation was for specific scenario. In this case the text box lost focus when the button was clicked and its value is changed to "test" after that, so the lost focus event is never triggered on the textbox with new value. Thanks for accepting my answer. – adnan Apr 10 '13 at 09:00