更新ObservableCollection中的值

问题描述

嘿,我有一个ObservableCollection,它由一个类,该类具有绑定到listbox的两个属性(字符串=用户和响应)。

我想首先将用户添加到列表框中,并以此添加:

for (int i = 0; i < ArrStrUser.Length; i++)
{
  Users.Add(new User() { input = ArrStrUser[i].Trim() });              
}

我想稍后将响应添加到各个用户。 如果这样做,它们将被添加到ObservableCollection中,但不会在列表框中更新。

Users[i].response = strOutput.Trim().Replace(Environment.NewLine," ");

ObservableCollecton

private ObservableCollection<Input> Users = new ObservableCollection<Input>();

班级:

public class Input
{
 public string user{ get; set; }
 public string response { get; set; }
}

XAML:

<ListBox x:Name="LBresponse" IsSynchronizedWithCurrentItem="True" ItemsSource="{Binding}" ItemTemplate="{StaticResource UserTemplate}" />

<DataTemplate x:Key="UserTemplate">
  <StackPanel Orientation="Horizontal">
    <TextBlock Text="{Binding Path= user}" Width="50"/>
      <TextBlock Text="{Binding Path= response}" />
    <Button Content="Delete" Click="DeleteUser_Clicked" HorizontalAlignment="Left"/>
  </StackPanel>
</DataTemplate>

解决方法

简单的解决方案

您的Input类需要实现INotifyPropertyChanged接口,并在更改属性值时调用PropertyChanged事件,以更新ListBoxObservableCollection仅“关心”添加或删除项目,它不处理项目的属性更改。

尝试像这样编辑输入类:

public class Input : INotifyPropertyChanged
{
    public string user{ get; set; }

    private string _response;
    public string Response{
        get => _response;
        set {
            _response = value;
            NotifyPropertyChanged();
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
 
    protected void NotifyPropertyChanged([CallerMemberName]string propertyName = "")
    {
        PropertyChanged?.Invoke(this,new PropertyChangedEventArgs(propertyName));
    }
}

现在更改Response属性将更新用户界面。


更好的解决方案

如果您也想在其他地方使用INotifyPropertyChanged实现,我也建议您将其INotifyPropertyChanged分成单独的类。或更妙的是,使用已有的库,例如James Montemagno的mvvm-helpers nuget package

这里是public class Input : ObservableObject { public string user{ get; set; } private string _response; public string Response{ get => _response; set => SetProperty(ref _response,value); } } implementation from that library

的链接

这是您的用法:

Action

它还支持传入OnChanged int i = 0; foreach (var innercell in cells) { int j = 0; foreach (var item in innercell) { if (j == cell.Col && cell.Row == i) { item.TagName = cell.TagName; item.Text = cell.Text; exist = true; break; } j++; } i++; } 和验证函数。

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...