Чтобы настроить стиль 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.
Как это работает:
- ListView ItemsSource связывается с клиентами
- ListView SelectedItem связывается с Customer
- ListView.ItemContainerStyle имеет DataTrigger, который связывается сDataContext.StyleType
- DataContext - это список объектов Customer с заданным пользователем свойством StyleType, которое инициализируется в выделенном фрагменте кода
- Команда кнопки очищает значение StyleType
- Нажатие на строку изменяет стиль следующей строки
- Клиент реализует INotifyPropertyChanged, который срабатывает при изменении StyleType
- 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();
}
}
}