简体   繁体   English

数据绑定似乎没有刷新

[英]Databindings don't seem to refresh

For some reason I'm really struggling with this.出于某种原因,我真的很挣扎。 I'm new to wpf and I can't seem to find the information I need to understand this simple problem.我是 wpf 的新手,似乎找不到理解这个简单问题所需的信息。

I am trying to bind a textbox to a string, the output of the programs activity.我试图将一个文本框绑定到一个字符串,即程序活动的输出。 I created a property for the string, but when the property changes, the textbox does not.我为字符串创建了一个属性,但是当属性更改时,文本框不会。 I had this problem with a listview, but created a dispatcher which refreshes the listview.我在列表视图中遇到了这个问题,但是创建了一个刷新列表视图的调度程序。

I must be missing some major point, because I thought one benefit of using wpf was not having to update controls manually.我一定遗漏了一些要点,因为我认为使用 wpf 的一个好处是不必手动更新控件。 I hope someone can send me in the right direction.我希望有人能把我送到正确的方向。

in windowMain.xaml.cs在 windowMain.xaml.cs

private string debugLogText = "initial value";

public String debugLog {
    get { return debugLogText; }
    set { debugLogText = value; }
}

in windowMain.xaml在 windowMain.xaml 中

x:Name="wndowMain"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
DataContext="{Binding RelativeSource={RelativeSource Self}}"

<TextBox Name="txtDebug" Text="{Binding ElementName=wndowMain, Path=debugLog}" />

Implement INotifyPropertyChanged on your class.在您的类上实现 INotifyPropertyChanged。 If you have many classes that need this interface, I often find it helpful to use a base class like the following.如果您有许多需要此接口的类,我经常发现使用如下所示的基类很有帮助。

public abstract class ObservableObject : INotifyPropertyChanged
{

    protected ObservableObject( )
    {
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged( PropertyChangedEventArgs e )
    {
        var handler = PropertyChanged;
        if ( handler != null ) {
            handler( this, e );
        }
    }

    protected void OnPropertyChanged( string propertyName )
    {
        OnPropertyChanged( new PropertyChangedEventArgs( propertyName ) );
    }

}

Then you just have to make sure you raise the PropertyChanged event whenever a property value changes.然后,您只需确保在属性值更改时引发 PropertyChanged 事件。 For example:例如:

public class Person : ObservableObject {

    private string name;

    public string Name {
        get {
              return name;
        }
        set {
              if ( value != name ) {
                  name = value;
                  OnPropertyChanged("Name");
              }
        }
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM