数据绑定到singleton类

时间:2014-10-08 22:31:30

标签: c# wpf data-binding

我在这里搜索了很多次,发现了一堆例子,但似乎无法使用。

我已经设置了一个解决方案,其中ViewModel通过定位器引用MainViewModel类。主视图模型类具有:

    public NotifyLog Log
    {
        get { return LogMgr.Instance.Log; }
    }

在里面。这允许我指定:

 <TextBox IsEnabled="True" Text="{Binding Log.Text, Mode=OneWay}"  />

NotifyLog定义为:

public class NotifyLog : INotifyPropertyChanged
{
    public NotifyLog()
    {
        _Log = new StringBuilder();
    }

    private void OnPropertyChanged(string property)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(property));
    }

    public event PropertyChangedEventHandler PropertyChanged;
    private StringBuilder _Log;

    public void Append(String Value)
    {
        _Log.Append(Value);
        OnPropertyChanged("Text");
    }

    public string Text
    {
        get { return _Log.ToString(); }
    } 

    public override string ToString()
    {
        return this.Text;
    }
}

对于应用程序的初始启动,将填充文本框,但OnPropertyChanged处理程序永远不会被绑定自动填充,因此不会检测到任何更改。我做错了什么,我只是不知道是什么......

谢谢你的时间, BLD

2 个答案:

答案 0 :(得分:1)

如果要在文本框中键入时更新日志,则需要将绑定模式更改为TwoWay。退出文本框时也会触发事件,而不是每个键入的字符都会触发。

如果要在更改日志时更新文本框,则需要在Text属性中添加setter并引发NotifyPropertyChanged事件(在setter中)。

还检查程序的输出是否存在绑定错误。

答案 1 :(得分:1)

到线:

<TextBox IsEnabled="True" Text="{Binding Log.Text, Mode=OneWay}"  />

尝试添加“UpdateSourceTrigger”,如下所示:

<TextBox IsEnabled="True" Text="{Binding Log.Text, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}"  />