简体   繁体   中英

WPF TextBox binding to multiple sources

Relatively new to WPF, so bear with me if I'm missing something obvious. I'm working on creating a "summary" textbox at the bottom of the window that describes the state of the application. The code for the property I want to bind to looks a bit like this:

public String WindowDescription
{
   get { return (radioButton.IsChecked == true ? "A " : "B ") + NameTextBox.Text 
+ " " + (cbRoute.SelectedItem != null? comboBox.SelectedItem.ToString() : ""); }
}

And I've bound it to the control like so:

<TextBox IsEnabled="False" Text="{Binding Path=WindowDescription}"/>

The binding doesn't work at all right now - each control referenced in WindowDescription has some default value, but even those values don't populate the TextBox. Like I said, I'm new to WPF, so feel free to point out anything missing from my example, no matter how obvious it may seem. Thanks.

A couple of things. First, ensure that your DataContext is set to the instance of the class that contains the WindowDescription property.

One would normally set this in the codebehind for the page. It can be set in XAML too, but I won't complicate my answer.

Secondly, databinding doesn't automatically see property value changes. A notification system needs to be setup in the class with the WindowDescription property.

Google "INotifyPropertyChanged" with Bing and see.

Otherwise, check this video out!

http://channel9.msdn.com/blogs/mtaulty/silverlight-databinding-ui-to-net-classes

Luke

If I had to guess, I'd guess that you did not set the DataContext of your TextBox (either directly, or by providing one for its parents somewhere).

The Binding Path is relative to the elements DataContext, and the default DataContext is null (and not the element itself, or its containing Window).

I am guessing Jens is right, did you set the model? ie

this.DataContext = model;

Where you model is anything, in our case where I work we are using ViewModel's and the MVVM pattern. You might look into something like Prism and Unity in the longer term but if you are just putting all your code in the .cs file for the XAML page here is an example.

    namespace DataContextTest

{

public partial class MainWindow : Window { public MainWindow() { this.DataContext = this; MyString = "Hi there..."; InitializeComponent(); }

public string MyString { get; set; }

} }

Then in the XAML bind to MyString like you have done in the other post and it should work, of course, again - there is no change notification at this point. I can post an example of that if you would like but I think you can google it and see many many simple examples.

Hope that was helpful.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM