简体   繁体   中英

How to create DataGrid Matrix from List Chars?

I display a List with chars in a TextBox , but the spacing is not uniform.

ABCDE
FGHIJ
KLMNO
PQRST
UVWXY


How can I bind it to a WPF DataGrid so it displays like a uniform 5x5 Matrix?

Or is there another way to make it uniform?

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

Besides the possibility to use a monospaced font, like

<TextBlock FontFamily="Lucida Console">
    <Run>ABCDE</Run>
    <LineBreak/>
    <Run>FGHIJ</Run>
    <LineBreak/>
    <Run>KLMNO</Run>
    <LineBreak/>
    <Run>PQRST</Run>
    <LineBreak/>
    <Run>UVWXY</Run>
</TextBlock>

you could use an ItemsControl with a UniformGrid:

<ItemsControl ItemsSource="ABCDEFGHIJKLMNOPQRSTUVWXY">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <UniformGrid Columns="5"/>
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding}" TextAlignment="Center"/>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

Although the XAML designer complains about the ItemsSource property, it will work because a string is an IEnumerable and the Text Binding automatically converts char to string .

You may of course also set the ItemsSource in code behind:

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"
};

or

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'
};

or of course

itemsControl.ItemsSource = "ABCDEFGHIJKLMNOPQRSTUVWXY";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM