无法在文本框的文本更改时更新静态绑定属性的值

本文关键字:文本 更新 静态绑定 属性 | 更新日期: 2023-09-27 18:36:39

我有以下标记。

<TextBox x:Name="Address" 
         Text="{Binding 
                  Source={x:Static local:MainWindow.Boundie},
                  Path=SomeProp,
                  Mode=TwoWay}">
</TextBox>

在后面的代码中,我有一个这样的静态属性。

Boundie = new Something { SomeProp = "old" };
static Something Boundie { get; set; }
public class Something { public String SomeProp { get; set; } }

我预计如果我在数据绑定文本框和断点中键入"new",该属性的属性会更改。事实并非如此。我是否以错误的方式使用模式?或者除了将其设置为 TwoWay 之外,我是否需要执行任何其他操作?还是在这种情况下,这种方法不合适?

无法在文本框的文本更改时更新静态绑定属性的值

如果您只需要从 GUI 更新数据对象,则INotifyPropertyChanged实现它不是强制性的。正如 Sonhja 所建议的那样,将 Boundie 属性初始化放在正确的位置非常重要。因此,您应该在静态构造器中插入Boundie = new Something { SomeProp = "old" };或在InitializeComponent();调用之前(在公共构造函数中)。

原因很简单:如果在InitializeComponent();调用后Boundie = new Something { SomeProp = "old" };,则绑定已尝试读取 Boundie 属性值(此时为 null)。

您的.xaml应如下所示:

<TextBox x:Name="Address" 
     Text="{Binding Path=Boundie.SomeProp, Mode=TwoWay}">
</TextBox>

您的.cs应如下所示:

public class YourClass : INotifyPropertyChanged
{
    private Boundie _boundie;
    // You need Boundie to be public
    public Boundie 
    { 
        get; 
        set
        {
             _boundie = value;
             OnPropertyChanged("Boundie");
        } 
    }
    public Main()
    {
        Boundie = new Something { SomeProp = "old" };
        // Initialize component AFTER you initialized your attribute
        InitializeComponent();
        DataContext = this;
    }
    [NotifyPropertyChangedInvocator]
    protected virtual void OnPropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
    }
}

注意:您的边界属性(SomeProp)必须是公开的。