简体   繁体   中英

How to set different Binding to each Array element? C# UWP

I managed to display my array in TextBlock - each [element] in separate row, but I would like to put each Array[index] element into separate TextBlock in the same Row, as long as it comes from same line, So:

  1. A file is accessed
  2. Lines are sorted
  3. Lines are split into words
  4. Each line is put on separate row

5. Each word from line is put into separate TextBlock but within the same row.

Here is my code:

public async void ReadFile()
    {
        var path = @"CPU.xls";
        var folder = Windows.ApplicationModel.Package.Current.InstalledLocation;

        var file = await folder.GetFileAsync(path);
        var readFile = await Windows.Storage.FileIO.ReadLinesAsync(file);
        foreach (string line in readFile.OrderBy(line =>
        {
            int lineNo;
            var success = int.TryParse(line.Split(';')[4], out lineNo);
            if (success) return lineNo;
            return int.MaxValue;
        }))
        {
            string[] splitLines = line.Split(';');

            for (int index = 0; index < splitLines.Length; index++)
            {
                itemsControl.Items.Add(splitLines[index]);
            }               
        }      
    }

As you can see above, I already did steps 1 - 4, unfortunately, at the moment each word goes into different row.

Here is bigger part of my xaml file:

<ItemsControl x:Name="itemsControl"
              ItemsSource="{Binding itemsControl}"
              FontSize="24">
                    <ItemsControl.ItemTemplate>
                        <DataTemplate>
                            <Grid Width="Auto"
                          Margin="0 12"
                                   HorizontalAlignment="Center">
                                <Grid.ColumnDefinitions>                                       
                                    <ColumnDefinition Width="Auto" />
                                    <ColumnDefinition Width="Auto" />
                                    <ColumnDefinition Width="Auto" />
                                    <ColumnDefinition Width="Auto" />
                                    <ColumnDefinition Width="Auto" />
                                </Grid.ColumnDefinitions>
                                <Grid.RowDefinitions>
                                    <RowDefinition Height="Auto" />                                        
                                </Grid.RowDefinitions>                                    
                                 <StackPanel Grid.Column="0"
                                    Grid.Row="0"
                                    Orientation="Horizontal">
                                    <TextBlock Text="{Binding }" />
                                </StackPanel>
                                <StackPanel Grid.Column="1"
                                    Grid.Row="0"
                                    Orientation="Horizontal">
                                    <TextBlock Text="{Binding }" />
                                </StackPanel>
                            </Grid>
                        </DataTemplate>
                    </ItemsControl.ItemTemplate>
                </ItemsControl>

I put two TextBlocks instead of 5 for now. How to make each of them getting different binding path to link with different array element?

----------UPDATE---------- I edited TextBlocks so each of them points to different array element like so:

<StackPanel Grid.Column="0"
            Grid.Row="0"
            Orientation="Horizontal">
          <TextBlock Text="{Binding Path=splitLines[0]}" />
</StackPanel>
<StackPanel Grid.Column="1"
            Grid.Row="0"
            Orientation="Horizontal">
          <TextBlock Text="{Binding Path=splitLines[1]}" />
</StackPanel>

I don't get any errors at this point, but unfortunately no data is displayed at all. Why binding to array element is not working?

You can do this quite easily setting ItemsPanel of ItemsControl

EDIT Added ItemTemplate to ItemsControl

Say you had a MainPage.xaml

<ItemsControl x:Name="WordsList"
              ItemsSource="{Binding listOfWords}">
    <!-- Ensures each item is displayed horizontally -->
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <StackPanel Orientation="Horizontal"></StackPanel>
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <!--if you want each line in seperate TextBlock with more control-->
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Grid>
               <TextBlock Text="{Binding}" FontSize="22" />
            </Grid>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

In code behind MainPage.xaml.cs

public sealed partial class MainPage : Page
{
    //Your intial string
    string words = "I am Line 1; I am Line 2; I am Line 3";

    //Using an ObservableCollection as works well with data binding
    public ObservableCollection<string> listOfWords { get; set; } = 
        new ObservableCollection<string>();

    public MainPage()
    {
        this.InitializeComponent();

        //set the DataContext to this page
        this.DataContext = this;

        Loaded += (s, args) =>
        {
            var splitWords = words.Split(';');
            foreach(var word in splitWords)
            {
                //each line is added to listOfWords and can then be accessed by the ItemsControl as the ItemsSource
                //is set to listOfWords
                listOfWords.Add(word);
            }                
        };
    }
}

EDIT2 to bind to the array you will need a public property eg

public string[] splitLines { get; set; }

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