I have a OneWayToSource binding that does not behave as I expected when I set the DataContext of the target control. The source property is assigned a default value instead of the value of the target control property.
I created a very simple program in a standard WPF window that illustrates my problem:
Xaml
<StackPanel>
<TextBox x:Name="tb"
Text="{Binding Path=Text,Mode=OneWayToSource,UpdateSourceTrigger=PropertyChanged}"
TextChanged="TextBox_TextChanged"/>
<Button Content="Set DataContext" Click="Button1_Click"/>
</StackPanel>
MainWindow.cs
public partial class MainWindow : Window
{
private ViewModel _vm = new ViewModel();
private void Button1_Click(object sender, RoutedEventArgs e)
{
Debug.Print("'Set DataContext' button clicked");
tb.DataContext = _vm;
}
private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
Debug.Print("TextBox changed to " + tb.Text);
}
}
ViewModel.cs
public class ViewModel
{
private string _Text;
public string Text
{
get { return _Text; }
set
{
Debug.Print(
"ViewModel.Text (old value=" + (_Text ?? "<null>") +
", new value=" + (value ?? "<null>") + ")");
_Text = value;
}
}
}
The TextBox tbstarts with a null DataContext, and therefore the binding should not do anything. Therefore, if I enter something into the text box, say "X", the ViewModel.Text property remains set to zero.
DataContext, , ViewModel.Text "X" TextBox.Text. ". , , , " Y" , "X" ViewModel.Text "XY".
( - - , , , "Y" ):
TextBox X
" DataContext"
ViewModel.Text( value = <null> , value =)
ViewModel.Text( value =, value = XY)
TextBox XY
ViewModel.Text "" "X", DataContext?
? - ? - ?
. , :
TextBox X
" DataContext"
ViewModel.Text( value = <null> , value = X)
ViewModel.Text( value = X, value = XY)
TextBox XY