【问题标题】:How to rename an item in a ListBox? [closed]如何重命名列表框中的项目? [关闭]
【发布时间】:2021-12-12 13:30:35
【问题描述】:

我希望用户能够直接重命名 ListBox 中的项目,其效果与我们在 Windows 的文件资源管理器中看到的示例相同。像这样:

有没有简单的方法来实现这一点?

感谢您的回答。

【问题讨论】:

  • ItemTemplate 中的文本框?你有没有尝试过?
  • 我的项目来自我自己制作的自定义类,所以我想知道除了更改我的项目类型之外,是否还有其他方法。
  • 为什么要“更改类型”?只需将 TextBox.Text 属性绑定到项目类的显示属性。请记住,我们无法神奇地看到您的代码。我们只知道您向我们展示的内容。
  • 谢谢,我明白了,但您是如何意识到这一点的?我只有一个<ListBox x:Name="ListBox">,并且在代码中类似于ListBox.ItemsSource = _list。我是 WPF 新手,绑定的概念对我来说仍然很陌生。
  • 您的_list 包含什么?是否有 TextBox 控件,您可以通过它编辑其内容?

标签: c# wpf listbox listboxitem


【解决方案1】:

假设您的项目类具有显示在 ListBox 中的读/写属性,例如

public class MyItem
{
    public string ItemText { get; set; }
}

您可以将 ListBox 的 ItemTemplate 中 TextBox 的 Text 属性绑定到该属性:

<ListBox x:Name="ListBox">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <TextBox Text="{Binding ItemText}"/>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

为了在您在 TextBox 中键入时更新 ItemText 属性(与 TextBox 失去焦点时相反),您必须设置 Binding 的 UpdateSourceTrigger:

<TextBox Text="{Binding ItemText, UpdateSourceTrigger=PropertyChanged}"/>

【讨论】:

  • 谢谢。但是 Binding 方法是如何知道 ItemText 来自 MyItem 对象的呢?
  • 因为您已将 MyItem 的集合分配给 ItemsSource 属性。 Binding 通过reflection 查找属性。
猜你喜欢
  • 1970-01-01
  • 2018-11-16
  • 1970-01-01
  • 2023-03-05
  • 2019-04-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多