我试图让ListView更改为我在ObvservableCollection中修改的任何值。
我目前正在使用此功能并将Collection绑定到我的ListView
private ObservableCollection<Task> _tasks = TaskInit.TaskCollection;
/// <summary>
/// Observable Collection to hold all tasks
/// </summary>
///
public ObservableCollection<Task> TasksCollection
{
get { return _tasks; }
set
{
_tasks = value;
NotifyPropertyChanged("TasksCollection");
}
}
问题是我是否使用以下代码:
TaskInit.TasksCollection[2].TaskNumber = "hi";
即使它应该发生变化,该值仍将与之前的值相同。
有人能说出我可能遇到的问题吗?
xaml的第一行是:
<ListView SelectionMode="Single" ScrollViewer.CanContentScroll="True" x:Name="listTasks" Margin="0,0,0,35" Background="{x:Null}" BorderBrush="{x:Null}" ItemsSource="{Binding TasksCollection, Mode=TwoWay}" ScrollViewer.HorizontalScrollBarVisibility="Disabled" ScrollViewer.VerticalScrollBarVisibility="Auto" BorderThickness="0" FontFamily="Myriad Pro" Foreground="{x:Null}" IsSynchronizedWithCurrentItem="True">
任务类:
public class Task : INotifyPropertyChanged
{
/// <summary>
///
/// </summary>
public string Module { get; set; }
/// <summary>
///
/// </summary>
public string FirstValue { get; set; }
/// <summary>
///
/// </summary>
public string SecondValue { get; set; }
/// <summary>
///
/// </summary>
public string ThirdValue { get; set; }
/// <summary>
///
/// </summary>
public int Minutes { get; set; }
/// <summary>
///
/// </summary>
public string TaskNumber { get; set; }
/// <summary>
///
/// </summary>
public string Story1 { get; set; }
/// <summary>
///
/// </summary>
public string Story2 { get; set; }
/// <summary>
///
/// </summary>
public string Story3 { get; set; }
/// <summary>
///
/// </summary>
public string NetworkAdapter { get; set; }
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
}
答案 0 :(得分:7)
ObservableCollection将处理在集合中添加或删除项目的情况,但它不会处理集合中项目属性发生更改的情况。 As per MSDN: 表示动态数据集合,在添加,删除项目或刷新整个列表时提供通知。
您需要确保您的Task类实现了INotifyPropertyChanged接口,并在其TaskNumber属性更改时触发PropertyChanged事件:
private string _taskNumber;
public string TaskNumber
{
get { return _taskNumber; }
set
{
if(_taskNumber!= value)
{
_taskNumber= value;
OnPropertyChanged("TaskNumber");
}
}
}
您的Task类实现了INotifyPropertyChanged,但是当它的属性值发生变化时,它实际上永远不会触发PropertyChanged事件。您需要在每个属性更改时手动调用OnPropertyChanged - 它不会自动发生。