Using a DataGrid as a custom ListView view mode

Oct 30, 2008 at 10:05 PM
Hi all. Has anyone had any success using a DataGrid as the basis of a custom view mode in a ListView?

I am trying to create an interface similar to that of Windows Explorer, in which a list of files can be viewed in different modes, such as thumbnails, tiles, etc. I am using a ListView, and I have all the modes working except "Details", for which I would like to use the new DataGrid control. I have had partial success, but I'm not sure if I'm on the right track. I have a ViewBase-derived class, as follows:
    public class DetailView : ViewBase
    {
        protected override object DefaultStyleKey
        {
            get {  return new ComponentResourceKey(GetType(), "DetailViewDefaultSyle"); }
        }
    }

The default style is as follows:
    <Style x:Key="{ComponentResourceKey
        TypeInTargetAssembly={x:Type local:DetailView},
        ResourceId=DetailViewDefaultSyle}"
        TargetType="{x:Type ListView}">
        <Setter Property="HorizontalContentAlignment"
            Value="Center"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate>
                    <Border>
                        <dg:DataGrid ItemsSource="{Binding Path=ItemsSource, RelativeSource={RelativeSource AncestorType=ListView}}"
                            AutoGenerateColumns="True"/>
                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

Using this, the DataGrid does show the list items as expected, but the item selection is not synchronised with the ListView's SelectedItems.
My guess is that using a ControlTemplate like that is not the right way to go about this, but maybe I just need to hook it up better to the ListView. If anyone has any insight on how this should be done, I would really appreciate some advice.