0

I have a series of TextBlock Controls, like this:

<TextBox Name="tb1"/>
<TextBox Name="tb2"/>
<TextBox Name="tb3"/>
<TextBox Name="tb4"/>

And I have a list of values that I'd like to bind to those text boxes, say in a list:

List<String> texts = new List<String>();
texts.Add("test1");
texts.Add("test2");
texts.Add("test3");
texts.Add("test4");

Currently, what I have to do is manually set the values of the TextBoxes, like this:

tb1.Text = texts[0];
tb2.Text = texts[1];
tb3.Text = texts[2];
tb4.Text = texts[3];

Is it possible to do this in a loop somehow? Perhaps change the XAML to take in a list or programatically get the TextBoxes? Thanks a lot in advance.

Joon
  • 9
  • 2

2 Answers2

5
<ItemsControl Items="{Binding myValues}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <TextBox Text="{Binding}"></TextBox>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

In your code behind declare a property:

public string myValues { get return new[] { "foo", "bar" }; }

and in the code behind constructor set this control to its datacontext:

this.DataContext = this;
Oliver Weichhold
  • 10,259
  • 5
  • 45
  • 87
0

You can access indexed values in your binding - no loop required. Check this previous SO answer from Ivan Towlson. Ivan uses a string indexer in that example, but you can use a numeric one as well.

Community
  • 1
  • 1
slugster
  • 49,403
  • 14
  • 95
  • 145