【发布时间】:2016-06-04 21:27:11
【问题描述】:
我有一个简单的 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>
【问题讨论】:
-
您是否在某处动态添加新项目?
-
ItemsControl i; i.Items.Refresh();怎么样 -
没有动态添加项目。只有 LastUpdated 属性的状态会发生变化。发生的情况是,当我为已更改的特定属性引发属性更改事件时,绑定仅发生一次,而不是针对我的示例中 ItemsSource 中的整个项目。有没有一种特殊的方法来为列表中的项目引发属性更改事件?
-
@TrustyCoder 看我的回答
-
如何将您的 List
更改为 ObservableCollection 用于您的条目。
标签: c# wpf refresh itemscontrol