双击更改列表框中作为项目模板WPF的复选框的名称

本文关键字:WPF 复选框 项目 列表 双击 | 更新日期: 2023-09-27 18:12:10

我已经在列表框中绑定了一个复选框。

现在我要修改复选框的名称,双击它。

如何更改复选框的名称(我必须给用户选项,以改变复选框的名称意味着用户将双击复选框的名称,然后名称将被文本框取代,然后用户可以添加名称。在模糊或合适的事件,它将被保存到数据库)

 <ListBox AlternationCount="2"   Width="140" Margin="18,63,480,24" Name="lstbxCuisines" ItemsSource="{Binding}" >
     <ListBox.ItemTemplate>
        <DataTemplate>
            <CheckBox  Name="chkCuisine" Height="20"  Margin="0,5,0,0" FontSize="12" Tag="{Binding CuisineId}" Content="{Binding Cuisine}"/>
        </DataTemplate>
    </ListBox.ItemTemplate>
    <ListBox.Resources>
        <Style  TargetType="{x:Type ListBoxItem}">
            <Style.Triggers>
                <Trigger Property="ItemsControl.AlternationIndex" Value="0">
                    <Setter Property="Background" Value="#ffffff"></Setter>
                </Trigger>
                <Trigger Property="ItemsControl.AlternationIndex" Value="1">
                    <Setter Property="Background" Value="#f1f6fe"></Setter>
                </Trigger>
            </Style.Triggers>
        </Style>
    </ListBox.Resources>
</ListBox>

双击更改列表框中作为项目模板WPF的复选框的名称

你可以给你的ComboBox添加MouseDoubleClick-Event:

            <DataTemplate>
                <CheckBox Name="chkCuisine" Height="20"  Margin="0,5,0,0" FontSize="12" Tag="{Binding CuisineId}" Content="{Binding Cuisine}" MouseDoubleClick="chkCuisine_MouseDoubleClick"/>
            </DataTemplate>

在eventandler中,您可以像这样更改Name:

    private void chkCuisine_MouseDoubleClick(object sender, MouseButtonEventArgs e)
    {
        ((ComboBox)sender).Name = "NewName";
    }

1路

<CheckBox.Style>
<Style TargetType="{x:Type CheckBox}">
    <EventSetter Event="MouseDoubleClick" Handler="CheckBoxDoubleClick"></EventSetter>
</Style>

protected void CheckBoxDoubleClick(object sender, MouseButtonEventArgs e)
    {
        CheckBox chk = e.Source as CheckBox;
        if (chk != null)
        {
            chk.Content = "Content Changed";
        }
    }

其他方式

<ListBox MouseDoubleClick="ListBox_MouseDoubleClick">
private void ListBox_MouseDoubleClick(object sender, MouseButtonEventArgs e)
    {
        var chk = FindParentControl<CheckBox>(e.OriginalSource as DependencyObject);
        if (chk != null)
        {
            ((CheckBox)chk).Content = "Content Changed";
        }
    }
private DependencyObject FindParentControl<T>(DependencyObject control)
    {
        if (control == null)
            return null;
        DependencyObject parent = VisualTreeHelper.GetParent(control);
        while (parent != null && !(parent is T))
        {
            parent = VisualTreeHelper.GetParent(parent);
        }
        return parent;
    }