开发者

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.


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!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜