gpt4 book ai didi

c# - 如何在编辑项目后刷新 ListView 控件?

转载 作者:行者123 更新时间:2023-11-30 14:38:47 29 4
gpt4 key购买 nike

我开始玩 wpf listview 控件。我创建了一个“添加”按钮和一个“编辑”按钮。“添加”按钮按预期工作 - 每当我将新项目添加到列表时,它就会显示出来。我的问题是“编辑”按钮 - 通知 listView 控件项目已更改的正确方法是什么? (它在附加代码中有效,我只是想知道是否有更好的方法)

这是我的代码:

Xaml:

<Window x:Class="WpfApplication5.MainWindow" Name="This"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525"
>
<Grid>
<ListView Name="Mylist"
ItemsSource= "{Binding ElementName=This, Path=People}"
SelectionMode="Single"
>
<ListView.View>
<GridView AllowsColumnReorder="false">
<GridViewColumn
Header="Name"
Width="Auto"
DisplayMemberBinding="{Binding Path=Name}" />
<GridViewColumn
Header="Id"
Width="Auto"
DisplayMemberBinding="{Binding Path=Id}" />
</GridView>
</ListView.View>
</ListView>
<StackPanel Orientation="Horizontal" Height="45" Margin="190,133,197,133">
<Button
Content="Add"
Click="AddButton_Click"
/>
<Button
Content="Edit"
Click="EditButton_Click"
/>
</StackPanel>
</Grid>
</Window>

代码隐藏:

namespace WpfApplication5
{
public class PersonalDetails
{
public string Name {get; set;}
public string Id {get; set;}
}

public partial class MainWindow : Window
{
private ObservableCollection<PersonalDetails> people = new ObservableCollection<PersonalDetails>();
public ObservableCollection<PersonalDetails> People
{
get { return this.people; }
}

public MainWindow()
{
PersonalDetails p1 = new PersonalDetails();
p1.Name = "Jeff";
p1.Id = "111";
people.Add(p1);
InitializeComponent();
}

private void AddButton_Click(object sender, System.Windows.RoutedEventArgs e)
{
PersonalDetails p2 = new PersonalDetails();
p2.Name = "Tom";
p2.Id = "222";
people.Add(p2);
}

private void EditButton_Click(object sender, System.Windows.RoutedEventArgs e)
{
PersonalDetails pItem = (PersonalDetails)Mylist.SelectedItem;
if (pItem == null)
{
return;
}
pItem.Name = "Dan";
Mylist.Items.Refresh();

}

}
}

最佳答案

您的 PersonalDetails 类应该实现 INotifyPropertyChanged界面。

然后,当 Name 属性更改并且您引发 PropertyChanged 事件时,WPF 绑定(bind)基础结构将通过刷新演示文稿来响应。

关于c# - 如何在编辑项目后刷新 ListView 控件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7371207/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com