【发布时间】:2011-03-31 15:13:51
【问题描述】:
我有一个 WPF ListView 控件,我正在为其动态创建列。其中一列恰好是 CheckBox 列。当用户直接单击 CheckBox 时,ListView 的 SelectedItem 不会更改。如果在 XAML 中声明了该复选框,我将添加对 Click 事件的处理以手动设置选择。但是,我很困惑,因为它是一个动态列。
<ListView
SelectionMode="Single"
ItemsSource="{Binding Documents}"
View="{Binding Converter={local:DocumentToGridViewConverter}}" />
转换器接收一个具有与之关联的属性的对象,有一个可以通过索引器引用的名称/值对。
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;
}
}
所以,我的问题是如何动态创建一个 CheckBox,当用户单击 CheckBox 时,它将导致 ListView 行被选中。
谢谢!
编辑:
这个问题类似,但没有动态片段:WPF ListView SelectedItem is null
【问题讨论】: