问题描述
嘿,我有一个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
事件,以更新ListBox
。 ObservableCollection
仅“关心”添加或删除项目,它不处理项目的属性更改。
尝试像这样编辑输入类:
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++;
}
和验证函数。