c# - TextBox 不更新 Observable 集合
问题描述
我搜索了大约 3 天的解决方案,但我无法完成。
我在一个类中有一个可观察的字符串集合(它从数据库中获取它的值,这是可行的)。这些绑定到 DataGrid,它为每个包含作为文本绑定的元素创建一个 TextBox。
我的代码后面可以更改可观察集合中的那些字符串,我可以删除单行,我可以添加行。一切都正确显示并在视图中更新。
但不知何故,如果我在运行时更改 TextBox 中的文本,则更新不会保存在可观察集合中。它始终保持不变。
这是我所拥有的:
XAML
<DataGrid ItemsSource="{Binding Path=DeviceType}">
<DataGrid.Columns>
<DataGridTemplateColumn>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBox Text="{Binding Path=., Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
我的课
class Test: INotifyPropertyChanged
{
private ObservableCollection<string> _deviceType = new ObservableCollection<string>();
public ObservableCollection<string> DeviceType
{
get
{
return _deviceType;
}
set
{
_deviceType = value;
OnPropertyChanged("DeviceType");
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
那么,我该怎么做才能更改 TextBox 中的文本也会更新 ObservableCollection 项?我发现一个帖子建议使用 BindingList 而不是 ObservableCollection,但它也不起作用。将字符串绑定到文本框当然可以,但为什么它不能与 ObservableCollection 一起使用?
例如:
如果我的 Observable 集合包含 3 个元素(“John”、“Doe”、“Mary”),则 DataGrid 会连续显示每个元素。如果我在那个盒子里写的是 Josh 而不是 John,我的 Collection 的第一个元素仍然包含“John”。
解决方案
Astring
是不可变的,这意味着它不能更改。
如果您将源集合的类型从ObservableCollection<string>
where ObservableCollection<YourClass>
is YourClass
a custom type with a public string
property 更改为,您可以绑定到并设置这个:
<TextBox Text="{Binding Path=TheProperty, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
public class YourClass : INotifyPropertyChanged
{
private string _theProperty;
public string TheProperty
{
get { return _theProperty; }
set { _theProperty = value; OnPropertyChanged(nameof(TheProperty); }
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
推荐阅读
- sqlite - Javafx:清除 SQLite 查询的 ResultSet,这样它就不会保留以前的结果
- powershell - 在 Windows 10 Powershell 中通过 F7 使命令历史弹出窗口工作
- javascript - 如何在javascript中获取频率值?
- json - 引起:org.apache.camel.InvalidPayloadException:
- sublimetext3 - Sublime Text 3 - 包控制 - 安装 | ImportError:没有名为“package_control”的模块
- javascript - 如何在javascript中计算本月和下个月的时间?
- c# - 更新标签文本仅使用给定文本的一部分
- angular - 如何在另一个应用程序中使用在一个角度应用程序中定义的自定义 html 元素
- tensorflow - 验证和训练期间 TensorFlow 中的批量标准化
- python - 下载google sheet,需要我先登录