Сетка в Windows Phone 7 - PullRequest
       9

Сетка в Windows Phone 7

3 голосов
/ 27 июля 2011

У меня есть код вида сетки ниже, у которого разделено на 3 столбца .Но у меня есть проблема с кодом.Когда несколько данных извлекается.Все данные в столбце 3 перекрываются. Как мне изменить приведенный ниже код так, чтобы он отображался один за другим под ним.

           //Define grid column, size

            Grid schedule = new Grid();

            foreach (var time in timeSplit)
            {
                timeList = time;
                //Column 1 to hold the time of the schedule
                ColumnDefinition scheduleTimeColumn = new ColumnDefinition();
                GridLength timeGrid = new GridLength(110);
                scheduleTimeColumn.Width = timeGrid;
                schedule.ColumnDefinitions.Add(scheduleTimeColumn);

                //Text block that show the time of the schedule
                TextBlock timeTxtBlock = new TextBlock();
                timeTxtBlock.Text = time;
                //Set the alarm label text block properties - margin, fontsize
                timeTxtBlock.FontSize = 28;
                timeTxtBlock.Margin = new Thickness(0, 20, 0, 0);
                //Set the column that will hold the time of the schedule
                Grid.SetColumn(timeTxtBlock, 0);

                schedule.Children.Add(timeTxtBlock);
            }

            foreach (var title in titleSplit)
            {
                titleList = title;

                //Column 2 to hold the title of the schedule
                ColumnDefinition scheduleTitleColumn = new ColumnDefinition();
                GridLength titleGrid = new GridLength(500);
                scheduleTitleColumn.Width = titleGrid;
                schedule.ColumnDefinitions.Add(scheduleTitleColumn);

                //Text block that show the title of the schedule
                TextBlock titleTxtBlock = new TextBlock();

                if (title.Length > 10)
                {
                    string strTitle = title.Substring(0, 10) + "....";
                    titleTxtBlock.Text = strTitle;
                }
                else
                {
                    titleTxtBlock.Text = title;
                }

                //Set the alarm label text block properties - margin, fontsize
                titleTxtBlock.FontSize = 28;
                titleTxtBlock.Margin = new Thickness(60, 20, 0, 0);
                //Set the column that will hold the title of the schedule
                Grid.SetColumn(titleTxtBlock, 1);

                schedule.Children.Add(titleTxtBlock);
                //scheduleListBox.Items.Add(schedule);
            }

            foreach (var category in categorySplit)
            {
                categoryList = category;

                //Column 3 to hold the image category of the schedule
                ColumnDefinition categoryImageColumn = new ColumnDefinition();
                GridLength catImgnGrid = new GridLength(70);
                categoryImageColumn.Width = catImgnGrid;
                schedule.ColumnDefinitions.Add(categoryImageColumn);

                TextBlock categoryTxtBlock = new TextBlock();
                categoryTxtBlock.Text = category;

                //set the category image and its properties - margin, width, height, name, background, font size
                Image categoryImage = new Image();
                categoryImage.Margin = new Thickness(-50, 15, 0, 0);
                categoryImage.Width = 50;
                categoryImage.Height = 50;
                if (category == "Priority")
                {
                    categoryImage.Source = new BitmapImage(new Uri("/AlarmClock;component/Images/exclamination_mark.png", UriKind.Relative));
                }
                else
                    if (category == "Favourite")
                    {
                        categoryImage.Source = new BitmapImage(new Uri("/AlarmClock;component/Images/star_full.png", UriKind.Relative));
                    }


                Grid.SetColumn(categoryImage, 2);
                schedule.Children.Add(categoryImage);
            }

            scheduleListBox.Items.Add(schedule);
        }

Ответы [ 4 ]

3 голосов
/ 27 июля 2011

Quickhorn ответ в основном правильный. Проблема в том, что вы создаете одну большую сетку вместо строки для каждого элемента в списке. Вот упрощенный пример вашего кода, в котором вместо этого используется объект модели и привязка данных.

Таким образом, вы можете легко оформить все в xaml, и это значительно упростит задачу.

Код сзади: MainPage.xaml.cs

public partial class MainPage : PhoneApplicationPage
{
    private ObservableCollection<Schedule> _schedules;

    public MainPage()
    {
        InitializeComponent();

        string[] timeSplit = new string[] { "One1", "Two2", "Three3" };
        string[] titleSplit = new string[] { "Title1", "Title2", "Title3" };
        string[] categorySplit = new string[] { "Priority", "Favourite", "Another" };

        _schedules = new ObservableCollection<Schedule>();

        for ( int i = 0; i < timeSplit.Length; i++ )
        {
            _schedules.Add( CreateSchedule( timeSplit[i], titleSplit[i], categorySplit[i] ) );
        }

        scheduleListBox.ItemsSource = _schedules;
    }

    private Schedule CreateSchedule( string time, string title, string category )
    {
        Schedule schedule = new Schedule
        {
            Time = time,
            Title = title,
            Category = category
        };

        if ( category == "Priority" )
        {
            schedule.ImageSource = "/AlarmClock;component/Images/exclamination_mark.png";
        }
        else if ( category == "Favourite" )
        {
            schedule.ImageSource = "/AlarmClock;component/Images/star_full.png";
        }

        return schedule;
    }
}

public class Schedule
{
    public string Time { get; set; }
    public string Title { get; set; }
    public string Category { get; set; }
    public string ImageSource { get; set; }
}

MainPage.xaml

<ListBox
    x:Name="scheduleListBox">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="Auto" />
                    <ColumnDefinition Width="Auto" />
                    <ColumnDefinition Width="Auto" />
                </Grid.ColumnDefinitions>
                <TextBlock
                    Text="{Binding Time}"/>
                <TextBlock
                    Text="{Binding Title}"
                    Grid.Column="1"/>
                <StackPanel
                    Orientation="Horizontal"
                    Grid.Column="2">
                    <TextBlock
                        Text="{Binding Category}"/>
                    <Image
                        Source="{Binding ImageSource}"/>
                </StackPanel>
            </Grid>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>
2 голосов
/ 27 июля 2011

Вы должны поместить StackPanel в каждый столбец и добавить элементы в StackPanels вместо сетки.

2 голосов
/ 27 июля 2011

На панели стека ваши элементы будут отображаться один над другим, однако вы можете потерять отношения между 3 столбцами.Вы также можете просто установить grid.row на индекс.

    int i = 0;
    foreach (var title in titleSpan)
    {
        {...} 
        Grid.SetColumn(titleTxtBlock, 1);
        Grid.SetRow(titleTxtBlock, i);

        schedule.Children.Add(titleTxtBlock);
    }

Сделайте это для каждого из ваших циклов for, и вы сохраните связь между элементами.Если между вашими элементами нет взаимосвязи (т. Е. Первый заголовок не связан с первой категорией, которая не связана с первым разом), вероятно, лучшим вариантом будет использование стековой панели.

0 голосов
/ 27 июля 2011

Вы можете добавить дополнительные столбцы в сетку, когда существует более 3 значений.

Может быть лучше использовать другой элемент управления для хранения данных, чтобы сделать его более понятным для пользователя, где прокручивать,чтобы увидеть больше.

Сначала придумайте дизайн, затем создайте его (и попросите о помощи)

...