我有一个简单的itemscontrol绑定到Entries对象列表 . 该按钮更新列表中每个项目的LastUpdated . 如何引发属性更改事件,以便在ItemsControl中更新LastUpdated字段 . 我简化了我的例子,只是想弄清楚绑定问题 . 我的真实样本使用PRISM和第三方控件 .
C#代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Input;
namespace TestItemsControl
{
public class Entry
{
public string Name { get; set; }
public DateTime LastUpdated { get; set; }
}
}
namespace TestItemsControl
{
public class TestViewModel: INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public List<Entry> Entries { get; set; }
public ICommand UpdateCmd { get; set; }
public TestViewModel()
{
this.Entries = new List<Entry>();
this.Entries.Add(new Entry{ Name = "1", LastUpdated = DateTime.Now });
this.Entries.Add(new Entry { Name = "2", LastUpdated = DateTime.Now });
this.Entries.Add(new Entry { Name = "3", LastUpdated = DateTime.Now });
}
public void Refresh()
{
if (this.PropertyChanged!= null)
{
PropertyChanged(this, new PropertyChangedEventArgs("Entries"));
}
}
}
}
XAML:
<Application x:Class="TestItemsControl.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:TestItemsControl"
StartupUri="MainWindow.xaml">
<Application.Resources>
<local:TestViewModel x:Key="viewModel"/>
</Application.Resources>
</Application>
<Window x:Class="TestItemsControl.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:TestItemsControl"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525" DataContext="{StaticResource viewModel}">
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<ItemsControl Grid.Row="0" ItemsSource="{Binding Entries}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Vertical"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid>
<TextBlock Text="{Binding Name}"/>
<TextBlock Text="{Binding LastUpdated}"/>
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
<Button Grid.Row="1" Content="Update" Click="Button_Click"/>
</Grid>
</Window>
4 回答
如果没有人订阅该活动,您必须检查是否为空
然后你必须重写你的
Entry
课程另外,将
List<Entry>
更改为ObservableCollection<Entry>
:这样您就不必调用Refesh函数 .
我想你必须在这里选择:
然后,无论何时您想要更新属性,您都可以:
或者如果要更新类中的每个属性:
如果您不确定要更新哪个属性,我建议您使用后者 .
您没有绑定UpdateCmd并在任何地方调用Refresh,除非它在Click处理程序中,但您应该使用MVVM方法来执行此操作 .
将Click事件处理程序更改为xaml中viewmodel的命令绑定,如下所示
然后在viewmodel的构造函数中,绑定创建一个新的RelayCommand或者ICommand实现类是什么样的,这样构造函数就会接受action delegate .
您也应该将Refresh更改为Update,以更新条目的时间戳 .
但是你真的应该只在Entry模型上实现INotifyPropertyChanged并在属性设置器上引发事件,绑定将被更新,而不会通知整个集合应该更新 .