2
我開始玩wpf listview控件。我創建了一個「添加」按鈕和一個「編輯」按鈕。 「添加」按鈕按預期工作 - 無論何時將新項目添加到顯示的列表中。 我的問題是與「編輯」按鈕 - 通知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();
}
}
}
謝謝, Li