You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WPF绑定报错‘Binding cannot be changed after it has been used’求助

问题解决步骤

1. 修复绑定代码的低级笔误

你的绑定代码里存在直接触发报错的错误:创建binding2后,误修改了已被使用的binding对象的Source属性,而不是给binding2设置数据源。这会导致已生效的binding被篡改,触发“Binding cannot be changed after it has been used”错误。

错误代码:

Binding binding = new Binding("Quantity");
binding.Source = noOfShares;
textBox00.SetBinding(TextBox.TextProperty, binding);
Binding binding2 = new Binding("Risk");
binding.Source = noOfShares; // 此处笔误,应设置binding2的Source
textBox02.SetBinding(TextBox.TextProperty, binding2);

修正后代码:

Binding binding = new Binding("Quantity");
binding.Source = noOfShares;
textBox00.SetBinding(TextBox.TextProperty, binding);

Binding binding2 = new Binding("Risk");
binding2.Source = noOfShares; // 改为设置binding2的数据源
textBox02.SetBinding(TextBox.TextProperty, binding2);

2. 修复绑定源类的冗余定义

NumberOfShares类继承了ObservableObject,但重复定义了PropertyChanged事件和OnPropertyChanged方法,导致INotifyPropertyChanged实现冲突,无法正确触发属性变更通知。删除子类中的冗余代码,直接复用父类实现:

修正后的NumberOfShares类:

public class NumberOfShares : ObservableObject
{
    private string _risk;
    private string _quantity;

    public NumberOfShares()
    {
    }

    public string Risk
    {
        get { return _risk; }
        set
        {
            _risk = value;
            OnPropertyChanged();
        }
    }

    public string Quantity
    {
        get { return _quantity; }
        set
        {
            _quantity = value;
            OnPropertyChanged();
        }
    }
}

ObservableObject类保持不变:

public class ObservableObject : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    public void OnPropertyChanged([CallerMemberName] string propertyname = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyname));
    }
}

3. 避免重复绑定的处理

如果绑定逻辑会被多次执行,每次设置新绑定前先清除旧绑定,确保使用全新的Binding实例:

// 清除旧绑定
BindingOperations.ClearBinding(textBox00, TextBox.TextProperty);
BindingOperations.ClearBinding(textBox02, TextBox.TextProperty);

// 创建新绑定并设置
Binding binding = new Binding("Quantity") { Source = noOfShares };
textBox00.SetBinding(TextBox.TextProperty, binding);

Binding binding2 = new Binding("Risk") { Source = noOfShares };
textBox02.SetBinding(TextBox.TextProperty, binding2);

关键原理说明

WPF的Binding对象是一次性使用的:一旦通过SetBinding关联到某个依赖属性,就不能再修改该Binding的任何属性,也不能重复绑定到其他控件。每次绑定必须创建全新的Binding实例。


内容的提问来源于stack exchange,提问作者Member 12823749

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 06:02:02