WPF绑定问题

时间:2011-05-29 09:23:47

标签: wpf

我有一个文本框,我需要将字符串绑定到。

<TextBox Name="txtDoc" Margin="5" Text ="{Binding Source={x:Static local:DocumentViewModel.FileText}, Path=FileText}">

FileText属性在另一个类上更改:

DocumentViewModel.GetInstance().FileText = File.ReadAllText(document.Path);

DocumentViewModel是一个包含Singleton的类:

public class DocumentViewModel : INotifyPropertyChanged
{
    private static string fileText;

    public string FileText
    {
        get { return fileText; }
        set
        {
            fileText = value; // Call OnPropertyChanged whenever the property is updated
            OnPropertyChanged("FileText");
        }
    }

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


    public event PropertyChangedEventHandler PropertyChanged = delegate { };

    private static DocumentViewModel instance = new DocumentViewModel();

    private DocumentViewModel() { }

    public static DocumentViewModel GetInstance()
    {
        return instance;
    }
}

我需要能够更改FileText属性的值并在文本框中反映此更改。 它不起作用。 我尝试使用TextBox作为静态属性,然后使用Onp

1 个答案:

答案 0 :(得分:2)

尝试将源设置为viewmodel而不是属性本身,并将instance属性设置为public? {Binding Source={x:Static local:DocumentViewModel.instance}, Path=FileText}

编辑包含一个完整的示例,对我有用:

Xaml:

<Window x:Class="Test.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:Test"
    Title="MainWindow" Height="350" Width="525"
    Loaded="Window_Loaded">
  <TextBox Name="txtDoc" Margin="5"
           Text="{Binding Source={x:Static local:DocumentViewModel.Instance}, Path=FileText}" />
</Window>

代码隐藏:

public partial class MainWindow : Window
{
  public MainWindow()
  {
    InitializeComponent();
  }

  private void Window_Loaded(object sender, RoutedEventArgs e)
  {
    DocumentViewModel.Instance.FileText = "Hello world!";      
  }
}

public class DocumentViewModel : INotifyPropertyChanged
{
  #region Singleton implementation

  // Static constructor to create the singleton instance.
  static DocumentViewModel()
  {
    DocumentViewModel.Instance = new DocumentViewModel();
  }

  public static DocumentViewModel Instance { get; private set; }

  #endregion

  private static string fileText;
  public string FileText
  {
    get { return fileText; }
    set
    {
      if (fileText != value)
      {
        fileText = value;
        OnPropertyChanged("FileText");
      }
    }
  }

  #region INotifyPropertyChanged

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

  public event PropertyChangedEventHandler PropertyChanged;

  #endregion
}