C# 以编程方式将TextBlock绑定到数组索引

C# 以编程方式将TextBlock绑定到数组索引,c#,binding,C#,Binding,我动态填充一个listView,因此我将每个文本框绑定到一个属性。我有点像: System.Windows.FrameworkElementFactory f = new System.Windows.FrameworkElementFactory(typeof(System.Windows.Controls.TextBlock)); f.SetValue(System.Windows.Controls.TextBox.FontWeightProperty, System.Windows.Fon

我动态填充一个listView,因此我将每个文本框绑定到一个属性。我有点像:

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);

例如,如果listview中填充了一个对象动物,并且该类动物内部有一个名为SomeProperty的属性,则listview中的该列将包含SomeProperty的值。例如,我尝试绑定到字符串数组。假设我有一个相同的类Animal,当我执行类似new Bindingarray[1]的操作时,该类Animal有一个字符串数组,但它没有绑定。只有当我对某个属性执行此操作时,它才具有约束力。或者有一种方法可以制作属性数组。如果我可以将数据绑定到数组索引,那就太好了。首先,您的集合应该是

       ObservableCollection<string> Animals
       {
           get;
           set;
       }
如果您希望动态设置listview,有一种更简单的方法:

        <ListView ItemsSource="{Binding Animals}">
        <ListView.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding}" Height="20" Width="100"></TextBlock>
            </DataTemplate>
        </ListView.ItemTemplate>
       </ListView>
您的dataContext应该设置为具有Animals属性的类,
如果您真的想在C中使用ObservaleCollection实现这一点,请尝试使用ObservaleCollection,但我确实建议使用此解决方案

正如我所知,您不能这样做,您必须在Binding中选择同样有效的属性名称。我创建了一个可索引数组属性,它成功了。我认为当绑定控件时,它们只能绑定到属性。因为我以前的数组不是一个属性,所以它不能工作。我是wpf的新手,我喜欢用代码做大部分事情。