Windows Presentation Foundation
A part of the .NET Framework that provides a unified programming model for building line-of-business desktop applications on Windows.
2,372 questions
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
Source thread: How to create an undertermined amount of grid columns?, answered by Peter Fleischer.
I have a text property bound to a TextBox. For each letter in the TextBox, I want to create a gird cell with a TextBlock inside it. So if I have a six letter word in the TextBox I get six grid columns with a TextBlock inside each column. How can I do this?
Hi,
Welcome to our Microsoft Q&A platform!
You can use ItemsTemplate in ControlTemplate of TextBox. Try following demo.
Xaml:
<Window x:Class="Window80"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp1"
mc:Ignorable="d"
Title="Window80" Height="450" Width="800">
<Window.DataContext>
<local:Window80VM/>
</Window.DataContext>
<StackPanel>
<TextBox Text="{Binding Word, UpdateSourceTrigger=PropertyChanged}" Margin="5"/>
<TextBox Margin="5">
<TextBox.Template>
<ControlTemplate>
<ItemsControl ItemsSource="{Binding LetterList}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Border BorderBrush="Red" BorderThickness="2" Width="20" Margin="5 0 5 0">
<TextBlock Text="{Binding}" HorizontalAlignment="Center"/>
</Border>
</DataTemplate>
</ItemsControl.ItemTemplate>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<VirtualizingStackPanel IsItemsHost="True"
Orientation="Horizontal"
VerticalAlignment="Top"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
</ControlTemplate>
</TextBox.Template>
</TextBox>
</StackPanel>
</Window>
and ViewModel:
Imports System.ComponentModel
Imports System.Runtime.CompilerServices
Public Class Window80VM
Implements INotifyPropertyChanged
Private _word As String
Public Property Word As String
Get
Return Me._word
End Get
Set(value As String)
Me._word = value
LetterList = (From item In value).ToList
OnPropertyChanged(NameOf(LetterList))
End Set
End Property
Public Property LetterList As List(Of Char)
Public Class Letter
Public Property l As String
End Class
Public Event PropertyChanged As PropertyChangedEventHandler Implements INotifyPropertyChanged.PropertyChanged
Private Sub OnPropertyChanged(<CallerMemberName> Optional propName As String = "")
RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(propName))
End Sub
End Class
Thanks.