How to bind a list of items to textbox inside stackpanel
I am new to Windows app development and trying to achieve something to display like this:
Tag no:1 Tag no:2 Tag no:3 //Left End of screen
Tag no:4 Tag no:5 ...so on.
Some like this :
I am doing this in Windows 10 universal app development.
Thanks in advance.
My Xaml code:
<StackPanel Orientation="Horizontal">
<TextBlock Text="{x:Bind comment_tags}" />
</StackPanel>
My c# code:
public List<string> comments_tags = new List<string>();
public MainPage()
{
this.InitializeComponent();
for(int i =0; i < 20; i++)
{
comments_tags.Add("Tag no: " + i);
}
}
New approach i tried:
public List<Border> comment_tags = new List<Border>();
for (int i = 0; i < 20; i++)
{
Border b_temp = new Border();
b_temp.CornerRadius = new CornerRadius(3);
b_temp.Background = new SolidColorBrush(Colors.Aqua);
TextBlock t = new TextBlock();
t.Text = "Tag no: " + i;
t.Foreground = new SolidColorBrush(Colors.Aqua)
b_temp.Child = t;
comments_tags.Add(b_temp);
}
your approach to deal with tags is not correct here, you do not want a text box here, you need a control that can understand what a tag is and how to deal with it.
Have a look here and here to understand how to implement this.
or a minimal implementation could be
<ItemsControl ItemsSource="{Binding Items}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Border BorderBrush="PowderBlue" CornerRadius="5" BorderThickness="2" Height="45" Margin="5" >
<TextBlock Text="{Binding}" VerticalAlignment="Center" Margin="5"/>
</Border>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
And code behind would be
public MainWindow()
{
InitializeComponent();
Items = new[] {"ABC", "DEF"};
this.DataContext = this;
}
public string[] Items
{ get; set; }
You cannot bind a List of strings directly to a TextBox control. As TextBox control displays only one string, all the items of a list can be added to a property which is a string and that property should be used to bind text to the TextBox.
You can bind Text to a TextBox as given below:
XAML
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding TBProperty}" />
</StackPanel>
C#
public List<string> comments_tags = new List<string>();
public string TBProperty
{
get;
set;
}
public MainWindow()
{
InitializeComponent();
this.DataContext = this;
for (int i = 0; i < 20; i++)
{
comments_tags.Add("Tag no: " + i);
}
foreach (string comment in comments_tags)
{
TBProperty += comment + " ";
}
}