首页 > 解决方案 > 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”。

标签: c#wpfdata-binding

解决方案


Astring是不可变的,这意味着它不能更改。

如果您将源集合的类型从ObservableCollection<string>where ObservableCollection<YourClass>is YourClassa custom type with a public stringproperty 更改为,您可以绑定到并设置这个:

<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));
        }
    }
}

推荐阅读