如何从列表字符创建DataGrid矩阵?

时间:2017-12-06 12:22:29

标签: c# wpf visual-studio xaml datagrid

我在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"/>

1 个答案:

答案 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";