2013-10-10 3 views
0

enter image description here Мне нужно отобразить таблицу, показывающую доступные категории, на которые может упасть элемент, и подсчет количества записей в каждой категории для текущего контекста данных.Более эффективная таблица сетки таблицы в WPF

Имена категорий будут в статическом классе enum для простоты, тогда я смогу найти в своем результирующем наборе имя категории (строка), чтобы определить счет.

Я прикладываю свой XAML Я использую стиль таблицы, как я хочу, но я не могу помочь, но думаю, что должен быть более элегантный способ. У кого-нибудь есть указатели?

<SolidColorBrush x:Key="SubTableHeading" Color="#BAA6BA" /> 
<SolidColorBrush x:Key="SubTableHeaderText" Color="#FFFFFF" /> 
<SolidColorBrush x:Key="SubTableText" Color="#888888" /> 
<SolidColorBrush x:Key="SubTableRow" Color="#FFFCFF" /> 
<SolidColorBrush x:Key="SubTableAlternateRow" Color="#FAEEFF" /> 
<SolidColorBrush x:Key="SubTableHighlightCell" Color="#EADEEF" /> 

<Grid Grid.Row="0" Grid.Column="1" Grid.RowSpan="7" Background="{StaticResource SubTableHeading}"> 
     <Grid.RowDefinitions> 
      <RowDefinition Height="18" /> 
      <RowDefinition Height="*" /> 
     </Grid.RowDefinitions> 
     <TextBlock Grid.Column="0" Text="Category breakdown" Padding="5,2,5,2" Foreground="{StaticResource SubTableHeaderText}" /> 
     <Grid Grid.Row="1" Background="{StaticResource SubTableRow}" > 
      <Grid.RowDefinitions> 
       <RowDefinition Height="13" /> 
       <RowDefinition Height="13" /> 
       <RowDefinition Height="13" /> 
       <RowDefinition Height="13" /> 
       <RowDefinition Height="13" /> 
       <RowDefinition Height="13" /> 
      </Grid.RowDefinitions> 
      <Grid.ColumnDefinitions> 
       <ColumnDefinition Width="5" /> 
       <ColumnDefinition Width="105" /> 
       <ColumnDefinition Width="25" /> 
       <ColumnDefinition Width="10" /> 
       <ColumnDefinition Width="105" /> 
       <ColumnDefinition Width="25" /> 
       <ColumnDefinition Width="10" /> 
       <ColumnDefinition Width="110" /> 
       <ColumnDefinition Width="25" /> 
      </Grid.ColumnDefinitions> 
      <TextBlock Grid.Column="1" Grid.Row="0" Foreground="{StaticResource SubTableText}">Category name</TextBlock> 
      <TextBlock Grid.Column="1" Grid.Row="1" Foreground="{StaticResource SubTableText}">Category name</TextBlock> 
      <TextBlock Grid.Column="1" Grid.Row="2" Foreground="{StaticResource SubTableText}">Category name</TextBlock> 
      <TextBlock Grid.Column="1" Grid.Row="3" Foreground="{StaticResource SubTableText}">Category name</TextBlock> 
      <TextBlock Grid.Column="1" Grid.Row="4" Foreground="{StaticResource SubTableText}">Category name</TextBlock> 
      <TextBlock Grid.Column="1" Grid.Row="5" Foreground="{StaticResource SubTableText}">Category name</TextBlock> 
      <TextBlock Grid.Column="2" Grid.Row="0" Width="25" Background="{StaticResource SubTableHighlightCell}" Foreground="{StaticResource SubTableText}" TextAlignment="Center">1</TextBlock> 
      <TextBlock Grid.Column="2" Grid.Row="1" Width="25" Background="{StaticResource SubTableHighlightCell}" Foreground="{StaticResource SubTableText}" TextAlignment="Center">1</TextBlock> 
      <TextBlock Grid.Column="2" Grid.Row="2" Width="25" Background="{StaticResource SubTableHighlightCell}" Foreground="{StaticResource SubTableText}" TextAlignment="Center">1</TextBlock> 
      <TextBlock Grid.Column="2" Grid.Row="3" Width="25" Background="{StaticResource SubTableHighlightCell}" Foreground="{StaticResource SubTableText}" TextAlignment="Center">1</TextBlock> 
      <TextBlock Grid.Column="2" Grid.Row="4" Width="25" Background="{StaticResource SubTableHighlightCell}" Foreground="{StaticResource SubTableText}" TextAlignment="Center">1</TextBlock> 
      <TextBlock Grid.Column="2" Grid.Row="5" Width="25" Background="{StaticResource SubTableHighlightCell}" Foreground="{StaticResource SubTableText}" TextAlignment="Center">1</TextBlock> 
      <TextBlock Grid.Column="4" Grid.Row="0" Foreground="{StaticResource SubTableText}">Category name</TextBlock> 
      <TextBlock Grid.Column="4" Grid.Row="1" Foreground="{StaticResource SubTableText}">Category name</TextBlock> 
      <TextBlock Grid.Column="4" Grid.Row="2" Foreground="{StaticResource SubTableText}">Category name</TextBlock> 
      <TextBlock Grid.Column="4" Grid.Row="3" Foreground="{StaticResource SubTableText}">Category name</TextBlock> 
      <TextBlock Grid.Column="4" Grid.Row="4" Foreground="{StaticResource SubTableText}">Category name</TextBlock> 
      <TextBlock Grid.Column="4" Grid.Row="5" Foreground="{StaticResource SubTableText}">Category name</TextBlock> 
      <TextBlock Grid.Column="5" Grid.Row="0" Width="25" Background="{StaticResource SubTableHighlightCell}" Foreground="{StaticResource SubTableText}" TextAlignment="Center">1</TextBlock> 
      <TextBlock Grid.Column="5" Grid.Row="1" Width="25" Background="{StaticResource SubTableHighlightCell}" Foreground="{StaticResource SubTableText}" TextAlignment="Center">1</TextBlock> 
      <TextBlock Grid.Column="5" Grid.Row="2" Width="25" Background="{StaticResource SubTableHighlightCell}" Foreground="{StaticResource SubTableText}" TextAlignment="Center">1</TextBlock> 
      <TextBlock Grid.Column="5" Grid.Row="3" Width="25" Background="{StaticResource SubTableHighlightCell}" Foreground="{StaticResource SubTableText}" TextAlignment="Center">1</TextBlock> 
      <TextBlock Grid.Column="5" Grid.Row="4" Width="25" Background="{StaticResource SubTableHighlightCell}" Foreground="{StaticResource SubTableText}" TextAlignment="Center">1</TextBlock> 
      <TextBlock Grid.Column="5" Grid.Row="5" Width="25" Background="{StaticResource SubTableHighlightCell}" Foreground="{StaticResource SubTableText}" TextAlignment="Center">1</TextBlock> 
      <TextBlock Grid.Column="7" Grid.Row="0" Foreground="{StaticResource SubTableText}">Category name</TextBlock> 
      <TextBlock Grid.Column="7" Grid.Row="1" Foreground="{StaticResource SubTableText}">Category name</TextBlock> 
      <TextBlock Grid.Column="7" Grid.Row="2" Foreground="{StaticResource SubTableText}">Category name</TextBlock> 
      <TextBlock Grid.Column="7" Grid.Row="3" Foreground="{StaticResource SubTableText}">Category name</TextBlock> 
      <TextBlock Grid.Column="7" Grid.Row="4" Foreground="{StaticResource SubTableText}">Category name</TextBlock> 
      <TextBlock Grid.Column="7" Grid.Row="5" Foreground="{StaticResource SubTableText}">Category name</TextBlock> 
      <TextBlock Grid.Column="8" Grid.Row="0" Width="25" Background="{StaticResource SubTableHighlightCell}" Foreground="{StaticResource SubTableText}" TextAlignment="Center">1</TextBlock> 
      <TextBlock Grid.Column="8" Grid.Row="1" Width="25" Background="{StaticResource SubTableHighlightCell}" Foreground="{StaticResource SubTableText}" TextAlignment="Center">1</TextBlock> 
      <TextBlock Grid.Column="8" Grid.Row="2" Width="25" Background="{StaticResource SubTableHighlightCell}" Foreground="{StaticResource SubTableText}" TextAlignment="Center">1</TextBlock> 
      <TextBlock Grid.Column="8" Grid.Row="3" Width="25" Background="{StaticResource SubTableHighlightCell}" Foreground="{StaticResource SubTableText}" TextAlignment="Center">1</TextBlock> 
      <TextBlock Grid.Column="8" Grid.Row="4" Width="25" Background="{StaticResource SubTableHighlightCell}" Foreground="{StaticResource SubTableText}" TextAlignment="Center">1</TextBlock> 
      <TextBlock Grid.Column="8" Grid.Row="5" Width="25" Background="{StaticResource SubTableHighlightCell}" Foreground="{StaticResource SubTableText}" TextAlignment="Center">1</TextBlock> 
     </Grid> 
    </Grid> 
+2

рассмотрите возможность отображения таблицы вместо xaml? – Bolu

+0

Похоже, что он лучше подходит для http: //codereview.stackexchange.com –

ответ

1

Вы можете изменить свой макет для использования ItemsControl. Вот прототип (без вашего стиля) ...

<ItemsControl ItemsSource="{Binding MyCollection}"> 
     <ItemsControl.ItemsPanel> 
      <ItemsPanelTemplate> 
       <WrapPanel Orientation="Horizontal" MaxWidth="450"/> 
      </ItemsPanelTemplate> 
     </ItemsControl.ItemsPanel> 
     <ItemsControl.ItemTemplate> 
      <DataTemplate> 
       <StackPanel Orientation="Horizontal" MaxWidth="150"> 
        <TextBlock Width="90" Text="{Binding CategoryName}" Margin="0,0,10,0"/> 
        <TextBlock Width="50" Text="{Binding CategoryCount}"/> 
       </StackPanel> 
      </DataTemplate> 
     </ItemsControl.ItemTemplate> 
    </ItemsControl> 

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

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

Класс контейнера будет выглядеть так ...

public class CategoryCounts: INotifyPropertyChanged 
{ 
    private int _categoryCount; 
    public int CategoryCount 
    { 
     [DebuggerStepThrough] 
     get { return _categoryCount; } 
     [DebuggerStepThrough] 
     set 
     { 
      if (value != _categoryCount) 
      { 
       _categoryCount = value; 
       OnPropertyChanged("CategoryCount"); 
      } 
     } 
    } 
    private string _categoryName; 
    public string CategoryName 
    { 
     [DebuggerStepThrough] 
     get { return _categoryName; } 
     [DebuggerStepThrough] 
     set 
     { 
      if (value != _categoryName) 
      { 
       _categoryName = value; 
       OnPropertyChanged("CategoryName"); 
      } 
     } 
    } 
} 

Наконец, вид Модель будет выглядеть примерно так ...

public class ViewModel:INotifyPropertyChanged 
{ 
    public ObservableCollection<CategoryCounts> MyCollection { get; set; } 
    public ViewModel() 
    { 
     MyCollection = new ObservableCollection<CategoryCounts>(); 
     MyCollection.Add(new CategoryCounts{CategoryName = "some category", CategoryCount = 22}); 
    } 
    #region INotifyPropertyChanged Implementation 
    public event PropertyChangedEventHandler PropertyChanged; 
    protected virtual void OnPropertyChanged(string name) 
    { 
     var handler = System.Threading.Interlocked.CompareExchange(ref PropertyChanged, null, null); 
     if (handler != null) 
     { 
      handler(this, new PropertyChangedEventArgs(name)); 
     } 
    } 
    #endregion 
} 

Вы можете получить почти те же результаты используя DataGrid или ListView, но эффект «обертывания» будет конфискован, потому что сетки используют «запись в строке», проходящую в вертикальном направлении, выложенную с соответствующими заголовками столбцов и т. д.

0

Вместо того, чтобы создать таблицу самостоятельно, используя сетку и много вручную размещенных текстовых полей, вы могли бы просто использовать инструмент, который был сделан для этого: A ListView с его View набор на GridView.

Если у вас есть полная модель для этих категорий, вы можете легко связаться с ними. Это будет выглядеть в XAML. Здесь Categories - это некоторое свойство в контексте данных, которое является списком элементов, которые сами имеют Name и свойство Number, с которым вы связываетесь в определениях GridViewColumn. Любой стиль можно также сделать с помощью GridViewColumn, или если вам нужно что-то более специальное, вы можете предоставить заказ CellTemplate.

<ListView ItemsSource="{Binding Categories}"> 
    <ListView.View> 
     <GridView> 
      <GridViewColumn Header="Category" DisplayMemberBinding="{Binding Name}" /> 
      <GridViewColumn Header="Number" DisplayMemberBinding="{Binding Number}" /> 
     </GridView> 
    </ListView.View> 
</ListView> 
+0

Отличный крик, будет ли стратегия здесь сделать свойство IList , связать ее с ListView, а затем использовать шаблоны данных для стилизации объектов CategoryViewModel, каждый из которых имеет поля Name и Count, все связанные стили и т. д. для каждой ячейки, , а затем примените общий стиль ListView на макете Gridview, чтобы получить заголовок, линии сетки, границу и т. д.? – NZJames

+0

@ user1122909 Это уже звучит неплохо, да. Я немного изменил свой ответ, чтобы дать вам пример того, как он работает. – poke

0
  1. для макета использования ItemControl с ItemTemlate.
  2. для стилизации (переднем плане, фон) использовать стиль.
  3. для заполнения/поля используйте настройку стиля вместо ненужных столбцов.
Смежные вопросы