我在List
中显示chars
TextBox
,但间距不统一。
A B C D E
F G H I J
K L M N O
P Q R S T
U V W X Y
如何将其绑定到WPF DataGrid
,使其显示为统一的5x5矩阵?
还是有另一种方法可以统一吗?
A B C D E
F G H I J
K L M N O
P Q R S T
U V W X Y
C#
public char A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y;
public List<char> myList = new List<char>()
{
A, B, C, D, E,
F, G, H, I, J,
K, L, M, N, O,
P, Q, R, S, T,
U, V, W, X, Y
}
public ObservableCollection<char> myCollection = new ObservableCollection<char>(myList);
XAML
<DataGrid x:Name="dataGrid"
HorizontalAlignment="Left"
Height="299"
Margin="191,399,0,0"
VerticalAlignment="Top"
Width="360"/>
答案 0 :(得分:1)
除了可以使用等宽字体外,例如
<TextBlock FontFamily="Lucida Console">
<Run>ABCDE</Run>
<LineBreak/>
<Run>FGHIJ</Run>
<LineBreak/>
<Run>KLMNO</Run>
<LineBreak/>
<Run>PQRST</Run>
<LineBreak/>
<Run>UVWXY</Run>
</TextBlock>
你可以使用带有UniformGrid的ItemsControl:
<ItemsControl ItemsSource="ABCDEFGHIJKLMNOPQRSTUVWXY">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<UniformGrid Columns="5"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding}" TextAlignment="Center"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
虽然XAML设计器抱怨ItemsSource
属性,但它会起作用,因为字符串是IEnumerable而Text Binding会自动将char
转换为string
。
您当然也可以在代码中设置ItemsSource:
itemsControl.ItemsSource = new List<string>()
{
"A", "B", "C", "D", "E",
"F", "G", "H", "I", "J",
"K", "L", "M", "N", "O",
"P", "Q", "R", "S", "T",
"U", "V", "W", "X", "Y"
};
或
itemsControl.ItemsSource = new List<char>()
{
'A', 'B', 'C', 'D', 'E',
'F', 'G', 'H', 'I', 'J',
'K', 'L', 'M', 'N', 'O',
'P', 'Q', 'R', 'S', 'T',
'U', 'V', 'W', 'X', 'Y'
};
或当然
itemsControl.ItemsSource = "ABCDEFGHIJKLMNOPQRSTUVWXY";