在C#和WPF,可以绑定一个数组的对象属性的一个元素?数组、绑定、属性、元素

2023-09-04 09:20:08 作者:不了解我,就别说我变了

例如,是否有可能给TextBlock的Text属性绑定到一个元素名称[2] String类型的?

For example, is it possible to bind a Textblock's Text property to an element Name[2] of type String?

推荐答案

我不知道你是什么意思究竟说:的元素名称[2]类型的字符串的,所以这里有两个可能的解决问题的方法:数组1和字符串1。数组1显示弓绑定到一个数组的元素,字符串1显示了如何在一个字符串显示一个单个字符。

I'm not sure what you mean exactly by saying:an element Name[2] of type String, so here are two possible solutions to your problem: Array1 and String1. Array1 show bow to bind to element of an array and String1 shows how to display one single character in a string.

code:

 public partial class MainWindow : Window
{
    private Array array1 = new[] {"test1", "test2", "test3"};
    public Array Array1 { get { return array1; } }

    public string string1 = "string";
    public string String1 { get { return string1; } }

    public MainWindow()
    {
        InitializeComponent();
        this.DataContext = this;
    }
}

XAML:

XAML:

 <StackPanel Orientation="Vertical">
    <TextBlock Text="{Binding Array1[0]}"/>
    <TextBlock Text="{Binding Array1[2]}"/>
    <TextBlock Text="{Binding String1[0]}"/>
    <TextBlock Text="{Binding String1[1]}"/>
</StackPanel>

希望有所帮助。

Hope that helps.