Home > other >  Why Can't Won't My WinForms Textbox bind?
Why Can't Won't My WinForms Textbox bind?

Time:03-12

Basically, I want to bind a textbox in my xaml with a variable, DisplayNumFilter, in my c#. I would like to initialize my textbox to 20. I've been looking through several stack overflow posts and have tried many things, which is the constructor is kind of a mess (I tried many things and just sort of left them there). However, nothing's worked. My apologies with any mistakes in regards to formatting or terminology, I am still very new to this.

Here is a snippet of my xaml:

<TextBox Name = "NumAccounts"
         Text="{Binding Path = DisplayNumFilter, Mode=TwoWay}" />


Here is a snippet of my c# code:

private string _displayNumFilter;

public string DisplayNumFilter{
get => _displayNimFilter;
set{
_displayNumFilter = value;
OnPropertyChanged("DisplayNumFilter");
}
}

public event PropertyChangedEventHandler PropertyChanged;

protected void OnPropertyChanged(string propertyName){
  PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}

public constructor(){ //it has a different name, I just use this as an example
   DisplayNumFilter = "20";
   InitializeComponent();
   Binding binding = new Binding();
   binding.Path = new PropertyPath("DisplayNumFilter");
   binding.Source = NumAccounts;
   BindingOperations.SetBinding(NumAccounts, TextBox.TextPoperty, binding);
   NumAccounts.Text = DisplayNumFilter;
}

CodePudding user response:

There are some issues with your code, but I will focus on the main:

Your binding source is wrong. From that the binding source it will start with the property path. To resolve the property DisplayNumFilter the source has to be set to this.

public SomeWindow()
{ 
   DisplayNumFilter = "20";
   InitializeComponent();
   Binding binding = new Binding();
   binding.Path = new PropertyPath("DisplayNumFilter");

   binding.Source = this; // -> was before NumAccounts;

   BindingOperations.SetBinding(NumAccounts, TextBox.TextPoperty, binding);
   NumAccounts.Text = DisplayNumFilter;
}

CodePudding user response:

The XAML markup Text="{Binding Path=DisplayNumFilter}" tries to bind to a DisplayNumFilter of the current DataContext of the TextBox control so you need to set the DataContext to an instance of the class where the DisplayNumFilter is defined.

This means that your constructor should look something like this:

public constructor() {
   DisplayNumFilter = "20";
   InitializeComponent();
   DataContext = this;
}

There is no reason to create a Binding object progrogrammtically if you use setup the bindings in the XAML markup.

  • Related