1

Существует ListView с колонками.

введите сюда описание изображения

Есть ли возможность скрывать колонки при помощи биндинга? Например, если бы у GridViewColumn было свойство Visibility, то можно было бы к нему привязаться.

Обратил внимание, что используют вариант с заданием ширины колонки значением 0. Но предполагаю, что можно и по другому как-то

1 Answers1

1

Можно реализовать с помощью IValueConverter и заданием нулевой Width.

Я использовал шаблон MVVM для реализации примера и вот такой вспомогательный класс для оповещения интерфейса об изменениях в свойствах.

public class NotifyPropertyChanged : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
        => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}

Класс данных

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
    public string Mail { get; set; }
}

View Model

public class MainViewModel : NotifyPropertyChanged
{
    private bool _ageVisible = true;
public bool AgeVisible
{
    get => _ageVisible;
    set
    {
        _ageVisible = value;
        OnPropertyChanged();
    }
}
private ObservableCollection<Person> _persons;

public ObservableCollection<Person> Persons
{
    get => _persons;
    set
    {
        _persons = value;
        OnPropertyChanged();
    }
}
public MainViewModel()
{
    Persons = new ObservableCollection<Person>
    {
        new Person {Name = "John Doe", Age = 42, Mail = "john@doe-family.com"},
        new Person {Name = "Jane Doe", Age = 42, Mail = "jane@doe-family.com"},
        new Person {Name = "Asmmy Doe", Age = 42, Mail = "sammy.doe@gmail.com"},
    };
}

}

Конвертер

public class GridViewWidthConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        => value is bool v && v ? null : (object)0;
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    => null;

}

View

<Window x:Class="WpfApp1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp1"
        mc:Ignorable="d"
        Title="MainWindow" Width="600" Height="300">
    <Window.DataContext>
        <local:MainViewModel/>
    </Window.DataContext>
    <Window.Resources>
        <local:GridViewWidthConverter x:Key="GridViewWidthConverter"/>
    </Window.Resources>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <CheckBox Content="Show Age" IsChecked="{Binding AgeVisible}" Margin="5"/>
        <ListView ItemsSource="{Binding Persons}" Grid.Row="1">
            <ListView.View>
                <GridView>
                    <GridViewColumn Header="Name" DisplayMemberBinding="{Binding Name}"/>
                    <GridViewColumn Header="Age" DisplayMemberBinding="{Binding Age}" Width="{Binding AgeVisible, Converter={StaticResource GridViewWidthConverter}}"/>
                    <GridViewColumn Header="Mail" DisplayMemberBinding="{Binding Mail}"/>
                </GridView>
            </ListView.View>
        </ListView>
    </Grid>
</Window>

введите сюда описание изображения

aepot
  • 49,560
  • 1
    Спасибо большое за ответ! Тоже реализовывал через установку ширины (подсмотрел). Думаю, что в итоге оставлю такой вариант – chesh111re Sep 18 '20 at 13:36