Miguel
Miguel

Reputation: 947

How to access a variable in DataContext from XAML (WPF)?

For example, i have an array in CodeBehind, that i want to bind to a DataGridComboBox in XAML.

First, i know i have to put the array in the DataContext(ok), but then how i access the array from XAML?

And how i make reference in the DataGridComboBox to bind the items from the array into the ComboBox?

My problem is working with DataContext, i can't really understand how to work with the DataContext.

Upvotes: 1

Views: 3406

Answers (1)

rrhartjr
rrhartjr

Reputation: 2114

In WPF, the DataContext is simply the object that provides the root path for Binding Expressions in the XAML.

So when you set DataContext, perhaps in the code-behind like:

string[] DataArray = new[] { "John", "Peter", "Paul" };`
this.DataContext = DataArray;

You can access it from the XAML like:

<TextBox Text="{Binding Path=Count}" />

You are now accessing the Count property on DataArray, by virtue of the DataContext property.

If you wanted a particular array element, you could specify an index:

<TextBox Text="{Binding Path=[0]}" />

If you wanted to use the array as the source to an element that supports a collection:

<ItemsControl ItemsSource="{Binding}" />

No arguments to a binding expression simply accesses DataContext directly, in this case, an array.

Hope that helps!

Upvotes: 3

Related Questions