0

I'm trying to figure out how to use a variable in code for databinding in a designer object. Example of what I'm trying to achieve: Say I have a string firstString and I set values to it in code. Now how do I make a TextBox to show this value through Databinding? I know I could just do TextBox.Text, but im looking for a Databinding way.

How about Generic lists? How would I populate a ListBox element in the designer with the objects from a list in the code by Databinding?

I went through this tutorial on how to link other designer objects to each other and some posts how to use whole classes as a DataContext. But I did not find an answer to this question in them.

Any help is appreciated.

Community
  • 1
  • 1
Esa
  • 1,636
  • 3
  • 19
  • 23
  • You are probably looking for a [ViewModelLocator](http://stackoverflow.com/questions/5462040/what-is-a-viewmodellocator-and-what-are-its-pros-cons-compared-to-datatemplates). – Jon May 24 '12 at 10:12
  • databinding work best with properties. create property wrapper around your variables. that will work fine with databindings. – JSJ May 24 '12 at 11:29
  • @Jon: I'm afraid that post went way above my head. – Esa May 25 '12 at 05:12
  • @Jodha: I did some searching on that, but again I found tutorials which show with whole classes. Could you perhaps give an example with single variables? – Esa May 25 '12 at 09:41

1 Answers1

1

WPF binding mechanism only support the properties. so the properties could be bind with other object but the variables are not allowed.

Element Name in binding is used to reference other controls, not variables in code behind. To reference variables in code behind, you need to assign that variable to a Control's Data Context property.

  private string firstString; // this is your field.

        public string FirstString // this is your property wrapper for the above field.
        {
            get { return firstString; }
            set { firstString = value; }
        }

XAML binding mec will only work with FirstString property not with the firststring variable.

also in C# concepts creating variables and accessing those outside is not recommended. the variables are usually designed for the local workout. where as if you want to share value of these variables the property making is the best and preferred solution.

JSJ
  • 5,653
  • 3
  • 25
  • 32
  • Thank you, I shall give this one a go. – Esa May 28 '12 at 05:51
  • Yup, this one was close on the target. Found full instructions from here: [link](http://www.codeproject.com/Articles/23487/WPF-and-Property-Dependencies-Part-I) – Esa May 28 '12 at 07:15