In meiner mvvm Anwendung habe ich eine Listenansicht. Ich möchte einige Spalten der Listenansicht anzeigen/ausblenden, abhängig vom Status der Checkbox "Alle Spalten anzeigen" (hier: Spalte1 sollte ein-/ausgeblendet werden).MVVM GridViewColumn Breite dynamisch setzen
Das ist mein sehr vereinfachter Code. Was ist falsch?! Offensichtlich funktioniert das nicht!
<Window x:Class="WpfApplication1.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:WpfApplication1"
mc:Ignorable="d"
Title="MainWindow" Height="200" Width="185">
<Window.Resources>
<local:ConverterHideListViewColumn x:Key="ConverterHideListViewColumn" />
</Window.Resources>
<Grid>
<ListView Height="100" Width="100">
<ListView.View>
<GridView>
<GridViewColumn Header="Col0" Width="40"/>
<GridViewColumn Header="Col1" Width="{Binding ShowAllColumns, Converter={StaticResource ConverterHideListViewColumn}}"/>
</GridView>
</ListView.View>
</ListView>
<CheckBox
Content="Show all columns"
IsChecked="{Binding ShowAllColumns, Mode=TwoWay}"
Margin="40,140,0,0">
</CheckBox>
</Grid>
</Window>
using System;
using System.ComponentModel;
using System.Windows;
using System.Windows.Data;
namespace WpfApplication1
{
public partial class MainWindow : Window
{
VM _vm;
public MainWindow()
{
InitializeComponent();
_vm = new VM();
this.DataContext = _vm;
}
}
/// <summary>
/// Dummy Viewmodel
/// </summary>
public class VM : INotifyPropertyChanged
{
private bool _bShowAllColumns;
public event PropertyChangedEventHandler PropertyChanged;
public VM()
{
ShowAllColumns = true;
}
public bool ShowAllColumns
{
get { return _bShowAllColumns; }
set { _bShowAllColumns = value; }
}
private void OnPropertyChanged (string propertyName)
{
var handler = PropertyChanged;
if (handler != null)
handler (this, new PropertyChangedEventArgs (propertyName));
}
}
/// <summary>
/// Converter for setting the ListView-Column width, depending on value VM.ShowAllColumns
/// </summary>
class ConverterHideListViewColumn : IValueConverter
{
public object Convert (object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
bool bShowAllColumns = false;
double dWidth = 0;
if (value is bool)
{
bShowAllColumns = (bool) value;
dWidth = bShowAllColumns? 40 : 0;
}
return dWidth;
}
public object ConvertBack (object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotSupportedException();
}
}
}
Ich sehe nicht, dass Sie ein Ereignis mit geänderter Eigenschaft auslösen, wenn 'ShowAllColumns' geändert wird. Wird 'Convert' auch ausgelöst, wenn das Kontrollkästchen geändert wird? –