WPF Set a TextBox property in code-behind

Hi I want to set the Text property of a Textbox by code behind. At the moment I do using XAML:

<TextBox x:Name="txtFilter" Text="{Binding FiltroFunzioni, Mode=OneWayToSource}" Grid.Row="0" />

As test I did this:

Binding b = new Binding();
b.Mode = BindingMode.OneWayToSource;
b.Path = new PropertyPath("Text");  //??
b.Source = PageViewModel.FiltroFunzioni;
BindingOperations.SetBinding(txtFilter, TextBlock.TextProperty, b);

The variable "FiltroFunzioni" is a string defined as property:

private string _filtroFunzioni = "";
public string FiltroFunzioni
    get { return _filtroFunzioni; }
        _filtroFunzioni = value;

Basically I dunno what kind of value should I set as PropertyPath. Any ideas?

>Solution :

You don’t need the PropertyPath here. If you just remove it, your binding should work.

That being said, you should bind in XAML wherever possible.

If your issue is that changes to FiltroFunzioni don’t update your textbox, that’s because your binding is specifically declared as OneWayToSource: that means that changing the UI changes the source, but changing the source doesn’t change the UI. If that isn’t what you want, set the Mode to something else, like "TwoWay" – then changes to the source change the UI, AND changes to the UI change the source.


If you really want to bind from your ViewModel instead of just using XAML, TwoWay binding requires utilizing the Path for some reason, when binding through C#. Either of the following solutions work:

b.Source = FiltroFunzioni;
b.Path = new PropertyPath(".");

b.Source = this;
b.Path = new PropertyPath("FiltroFunzioni");

Note that with TwoWay binding you have to either initialize your FiltroFunzioni by setting the TextBox.Text property in your XAML, or setting FiltroFunzioni after the binding was initialized. Otherwise, WPF will immediately override it from the (by default empty) Text in your TextBox.

Leave a Reply