I have a WPF ListView control for which I am dynamically creating columns. One of the columns happens to be a CheckBox column. When the user directly clicks on the CheckBox the ListView's SelectedItem is not changed. Had the checkbox been declared in XAML I would have added handling for the Click event to manually set the selection. However, I'm stumped since it's a dynamic column.
<ListView
SelectionMode="Single"
ItemsSource="{Binding Documents}"
View="{Binding Converter={local:DocumentToGridViewConverter}}" />
The converter takes in an object that has Properties associated with it, there is a name/value pair that can be referenced through indexers.
public class DocumentToGridViewConverter : MarkupExtension, IValueConverter
{
private static DocumentToGridViewConverter mConverter;
public object Convert( object value, Type targetType, object parameter, CultureInfo culture )
{
GridView gridView = null;
Document document = value as Document;
if( document != null )
{
// Create a new grid view.
gridView = new GridView();
// Add an isSelected checkbox complete with binding.
var checkBox = new FrameworkElementFactory( typeof( CheckBox ) );
gridView.Columns.Add( new GridViewColumn
{
Header = string.Empty, // Blank header
CellTemplate = new DataTemplate { VisualTree = checkBox },
} );
// Add the rest of the columns from the document properties.
for( int index = 0; index < document.PropertyNames.Length; index++ )
{
gridView.Columns.Add( new GridViewColumn
{
Header = document.PropertyNames[index];
DisplayMemberBinding = new Binding(
string.Format( "PropertyValues[{0}]", index ) )
} );
}
}
return gridView;
}
public object ConvertBack( object value, Type targetType, object parameter, CultureInfo culture )
{
throw new NotImplementedException();
}
public override object ProvideValue( IServiceProvider serviceProvider )
{
if( mConverter == null )
{
mConverter = new DocumentToGridViewConverter();
}
return mConverter;
}
}
So, my question is how do I dymaically create a CheckBox that will cause the ListView row to be select when the user clicks on the CheckBox.
Thanks!
EDIT:
This question are similar, but doesn't have the dynamic piece: WPF ListView SelectedItem is null