需要帮助创建wpf listview自定义控件

时间:2017-04-18 19:10:21

标签: c# wpf xaml listview

我想创建一个WPF自定义控件继承ListView。我知道如何在普通的WPF窗口中构建listview,但是在自定义控件的Generic.xaml中,我不知道该怎么做。
你能帮我把下面的listview变成自定义控件的Generic.xaml格式吗? 谢谢。

<ListView x:Name="listView"
          ScrollViewer.HorizontalScrollBarVisibility="Disabled"
          ScrollViewer.VerticalScrollBarVisibility="Auto"
          SelectionMode="Single"
          ItemContainerStyle="{DynamicResource MyListViewItemContainerStyle}"
          ItemsSource="{TemplateBinding ItemsSource}" >
    <ListView.Resources>
        <DataTemplate x:Key="FirstColumnDataTemplate" >
            <Border BorderBrush="#FFABADB3" BorderThickness="1,0,1,1" Margin="-6,0,-6,0">
                <Grid Margin="6,2,6,2">
                    <ContentPresenter ContentTemplate="{Binding FirstColumnItemTemplate, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=local:CustomControl1}}" 
                                      Focusable="False" 
                                      RecognizesAccessKey="True"/>
                </Grid>
            </Border>
        </DataTemplate>
        <DataTemplate x:Key="SecondColumnDataTemplate">
            <Border BorderBrush="#FFABADB3" BorderThickness="0,0,1,1" Margin="-6,0,-6,0">
                <Grid Margin="6,2,6,2">
                    <ContentPresenter ContentTemplate="{Binding SecondColumnItemTemplate, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=local:CustomControl1}}" 
                                      Focusable="False" 
                                      RecognizesAccessKey="True"/>
                </Grid>
            </Border>
        </DataTemplate>
        <Style x:Key="MyListViewItemContainerStyle" TargetType="{x:Type ListViewItem}">
            <Setter Property="HorizontalContentAlignment" Value="Stretch" />
            <Setter Property="VerticalContentAlignment" Value="Stretch" />
            <Setter Property="Margin" Value="0,-4,0,0"/>
        </Style>
    </ListView.Resources>
    <ListView.View>
        <GridView AllowsColumnReorder="False">
            <GridViewColumn x:Name="FirstColumn"
                            Header="{TemplateBinding FirstColumnHeader}"
                            CellTemplate="{DynamicResource FirstColumnDataTemplate}"/>
            <GridViewColumn x:Name="SecondColumn"
                            Header="{TemplateBinding SecondColumnHeader}" 
                            CellTemplate="{DynamicResource SecondColumnDataTemplate}"/>
        </GridView>
    </ListView.View>
</ListView>

FirstColumnHeader,SecondColumnHeader是字符串依赖属性。 FirstColumnItemTemplate,SecondColumnItemTemplate是自定义控件的DataTemplate依赖项属性。
自定义控件本身继承ListView,如:

public class CustomControl1 : ListView

0 个答案:

没有答案