Question

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>
Was it helpful?

Solution

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"/>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top