双击时如何使listview列可编辑?

时间:2018-03-11 01:59:35

标签: c# .net wpf listview

所以我有一个带有几个标题的列表视图,当设置数据时,我希望可以选择双击其中一列来编辑值。 这是可能的,如果是这样,这样做的正确方法是什么?

<ListView Name="LvProducts" Margin="224,204,10,35">
            <ListView.View>
                <GridView>
                    <GridViewColumn Header="ID" Width="120" DisplayMemberBinding="{Binding ID}" />
                    <GridViewColumn Header="SKU" Width="50" DisplayMemberBinding="{Binding SKU}" />
                    <GridViewColumn Header="Name" Width="150" DisplayMemberBinding="{Binding Name}" />
                    <GridViewColumn Header="Description" Width="150" DisplayMemberBinding="{Binding Description}" />
                    <GridViewColumn Header="In Stock" Width="150" DisplayMemberBinding="{Binding InStock}" />
                    <GridViewColumn Header="Price" Width="150" DisplayMemberBinding="{Binding Price}" />
                    <GridViewColumn Header="Images" Width="150" DisplayMemberBinding="{Binding Images}" />
                </GridView>
            </ListView.View>
        </ListView>

1 个答案:

答案 0 :(得分:0)

Sajeetharan在这篇文章中回答how to make the column editable in ListView?

为GridViewColumn.CellTemplate创建名为EditBox的自定义控件。

在普通模式下,TextBlock用于显示内容;在编辑模式下,将弹出一个TextBox进行编辑。

来自Control的类

public class EditBox : Control
{
            static EditBox()
            {              
            public static readonly DependencyProperty ValueProperty =
                    DependencyProperty.Register(
                            "Value",
                            typeof(object),
                            typeof(EditBox),
                            new FrameworkPropertyMetadata());
}

为IsEditing添加依赖项属性。

public static DependencyProperty IsEditingProperty =
                    DependencyProperty.Register(
                            "IsEditing",
                            typeof(bool),
                            typeof(EditBox),
                            new FrameworkPropertyMetadata(false)
                            );

Custom EditBox的样式:

<Style x:Key="{x:Type l:EditBox}" TargetType="{x:Type l:EditBox}" >
      <Setter Property="HorizontalAlignment" Value="Left"  />
      <Setter Property="Template">
        <Setter.Value>
          <ControlTemplate TargetType="{x:Type l:EditBox}">
                <TextBlock x:Name="PART_TextBlockPart" 
                     Text="{Binding Path=Value, RelativeSource = {RelativeSource TemplatedParent}}">
                </TextBlock>
          </ControlTemplate>
        </Setter.Value>
      </Setter>
    </Style>

在您的Xaml中,您可以将EditBox放在每一列中:

//Example with first column
<GridViewColumn Header="ID" Width="120" DisplayMemberBinding="{Binding ID}">
        <GridViewColumn.CellTemplate>
            <DataTemplate>
               <i:EditBox>
            </DataTemplate>
        </GridViewColumn.CellTemplate>
    </GridViewColumn>