Bind TextBlock to array index programatically
I am filling a listView dynamically and as a result I am binding each textbox to a property. I have something like开发者_开发百科:
System.Windows.FrameworkElementFactory f = new System.Windows.FrameworkElementFactory(typeof(System.Windows.Controls.TextBlock));
f.SetValue(System.Windows.Controls.TextBox.FontWeightProperty, System.Windows.FontWeights.Normal);
Binding myBinding = new Binding("SomeProperty");
f.SetBinding(System.Windows.Controls.TextBlock.TextProperty, myBinding);
If the listview is filled with an object Animal for example and that class Animal has a property inside named SomeProperty then that column in the listview will contain the value of SomeProperty. What I am trying to do is to bind to a string array for example. Let's say I have the same class Animal and that animal has a string array when I do something like new Binding("array[1]") it does not bind. It only binds when I do it to a property. Or maybe there is a way of making a property array. It will be nice if I could bind data to an array index
First of all your collection should be
ObservableCollection<string> Animals
{
get;
set;
}
And if you want your listview set dynamically there is easier aproach:
<ListView ItemsSource="{Binding Animals}">
<ListView.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding}" Height="20" Width="100"></TextBlock>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
And your dataContext should be set to the class with Animals property, if you really want to do that in C# try with ObservableCollection but I really suggest this solution
精彩评论