стайлинг n-го элемента в списке? - PullRequest
1 голос
/ 06 марта 2011

У меня есть внешнее свойство 'current' (int), которое представляет текущий индекс коллекции. У меня есть просмотр списка, который отображает эту коллекцию. Я хочу иметь возможность стилизовать «n-й» элемент коллекции в зависимости от значения «current», т. Е. Если current равен 3, выделить 4-й элемент в коллекции (index = 3) и т. Д. Как это сделать

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

1 Ответ

0 голосов
/ 06 марта 2011

Чтобы настроить стиль ListView, вы можете создать DataTrigger, который привязывается к свойству DataContext представления для изменения текущего стиля.В этом примере код изменяет фон.

<ListView.ItemContainerStyle>
  <Style TargetType="ListViewItem">
    <Setter Property="Background" Value="Aqua"/>
      <Style.Triggers>
        <DataTrigger Binding="{Binding Path=DataContext.StyleType, RelativeSource={RelativeSource Self}}" Value="1">
          <Setter Property="Background" Value="Chartreuse"/>
        </DataTrigger>
      </Style.Triggers>
  </Style>
</ListView.ItemContainerStyle>

Я добавил большую часть кода здесь, чтобы вы могли получить как можно более полную картину происходящего, но я пропустил общие базовые классы MVVM.

Как это работает:

  1. ListView ItemsSource связывается с клиентами
  2. ListView SelectedItem связывается с Customer
  3. ListView.ItemContainerStyle имеет DataTrigger, который связывается сDataContext.StyleType
  4. DataContext - это список объектов Customer с заданным пользователем свойством StyleType, которое инициализируется в выделенном фрагменте кода
  5. Команда кнопки очищает значение StyleType
  6. Нажатие на строку изменяет стиль следующей строки
  7. Клиент реализует INotifyPropertyChanged, который срабатывает при изменении StyleType
  8. DataTrigger изменяет фон каждого ListViewItem

Вот XAMLпосмотрите на DataTrigger:

<Window x:Class="ListViewScrollPosition.Views.ScrollBarwindow"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  Title="Style on Model" Height="300" Width="300">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition/>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>
        <ListView 
            Grid.Row="0"
            SelectedItem="{Binding Customer}"
            ItemsSource="{Binding Customers}" x:Name="myListView">
            <ListView.ItemContainerStyle>
                <Style TargetType="ListViewItem">
                    <Setter Property="HorizontalContentAlignment" Value="Stretch" />
                    <Setter Property="Background" Value="Aqua"/>
                    <Style.Triggers>
                        <DataTrigger Binding="{Binding Path=DataContext.StyleType, RelativeSource={RelativeSource Self}}" Value="1">
                            <Setter Property="Background" Value="Pink"/>
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </ListView.ItemContainerStyle>
            <ListView.View>
                <GridView>
                    <GridViewColumn Header="First Name"
                                    DisplayMemberBinding="{Binding FirstName}" />
                    <GridViewColumn Header="Last Name"
                                    DisplayMemberBinding="{Binding LastName}" />
                    <GridViewColumn Header="Style Type"
                                    DisplayMemberBinding="{Binding StyleType}" />
                </GridView>
            </ListView.View>
        </ListView>
        <Button Grid.Row="1" Content="Change Style" Command="{Binding Path=AlterStyle}"/>
    </Grid>
</Window>

Вот модель представления, которую View использует для получения клиентов и другихter Значение StyleType:

using System.Collections.Generic;
using System.Windows.Input;
using ListViewScrollPosition.Commands;
using ListViewScrollPosition.Models;

namespace ListViewScrollPosition.ViewModels
{
 public class MainViewModel : ViewModelBase
 {
   private DelegateCommand _alterStyleCommand;

   public MainViewModel()
   {
   }

   public ICommand AlterStyle
   {
     get
     {
       if (_alterStyleCommand == null)
        {
          _alterStyleCommand = new DelegateCommand(AlterStyleCommand);
        }
       return _alterStyleCommand;
     }
   }

   private void AlterStyleCommand()
   {
    foreach (var customer in Customers)
    {
      customer.StyleType = 0;
    }
   }

   private void ApplyStyleToNextRow(Customer currentCustomer)
   {
     bool setNext = false;
     foreach (var customer in Customers)
     {
       if (setNext)
       {
         customer.StyleType = 1;
         setNext = false;
       }
       else
       {
         customer.StyleType = 0;
       }

       if (currentCustomer == customer)
       {
         setNext = true;
       }
     }
   }

   private List<Customer> _customers = Customer.GetSampleCustomerList();
   public List<Customer> Customers
   {
     get
     {
        return _customers;
     }
   }

   private Customer _customer = null;
   public Customer Customer
   {
     get
     {
       return _customer;
     }
     set
     {
       _customer = value;
       ApplyStyleToNextRow(_customer);
       OnPropertyChanged("Customer");
     }
   }
 }
}

Вот модель, ViewModelBase реализует INotifyPropertyChanged, StyleType запускает OnPropertyChanged при изменении, обновляя каждый ListViewItem:

using System;
using System.Collections.Generic;

namespace ListViewScrollPosition.Models
{
  public class Customer : ViewModels.ViewModelBase
  {
    public String FirstName { get; set; }
    public String LastName { get; set; }

    private int _style;
    public int StyleType
    {
      get { return _style;}
      set
      {
        _style = value;
        OnPropertyChanged("StyleType");
      }
    }

    public Customer(String firstName, String lastName, int styleType)
    {
      this.FirstName = firstName;
      this.LastName = lastName;
      this.StyleType = styleType;
    }

    public static List<Customer> GetSampleCustomerList()
    {
     return new List<Customer>(new Customer[4] {
            new Customer("A.", "Zero", 0), 
            new Customer("B.", "One", 1),
            new Customer("C.", "Two", 2),
            new Customer("D.", "Three", 1)
        });
    }
  }
}

Вот код, гдеЯ устанавливаю DataContext:

using System.Windows;
namespace ListViewScrollPosition.Views
{
  public partial class ScrollBarwindow : Window
  {
    public ScrollBarwindow()
    { 
      InitializeComponent();
      DataContext = new ViewModels.MainViewModel();
    }
  }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...