【问题标题】:Write To Output message (C# => TextBox)写入输出消息(C# => TextBox)
【发布时间】:2019-02-25 13:37:38
【问题描述】:

我有文本框:

 <TextBox  DockPanel.Dock="Bottom"               
           FontFamily="Consolas"
           Text="{Binding Path=Output}"
           VerticalScrollBarVisibility="Visible"
           HorizontalScrollBarVisibility="Auto"
           AcceptsReturn="True"
           AcceptsTab="True" /> 

在这个 TextBox 里面我想发送一些/添加消息:

public string Output { get; set; }
public void WriteToOutput(string message)
{
 Output += DateTime.Now.ToString("dd.MM HH:mm:ss") + " " + message + Environment.NewLine;
}     

public void LoadExcelFile()
{
  WriteToOutput("Start....")
  //SOME CODE
  WriteToOutput("End....")
}

输出应如下所示:

Start...
End...

但它没有显示在 TextBox 中的文本。是什么原因?

更新:我的 MainViewModel.cs:

[AddINotifyPropertyChangedInterface]
public class MainViewModel
{
....
}

我正在使用PropertyChanged.Fody

【问题讨论】:

  • OnPropertychanged。你需要实现 INotifyPropertyChanged
  • 你没有在你的虚拟机中实现 INPC?
  • 是否引发了 propertychanged 事件? (哈哈哈三个同时回答)
  • 我有 [AddINotifyPropertyChangedInterface]

标签: c# wpf data-binding textbox output


【解决方案1】:

您缺少INotifyPropertyChanged 实现。

一个工作示例:

using System.ComponentModel;

public partial class MainWindow : Window, INotifyPropertyChanged
{
    private string output;
    public string Output
    {
        get { return output; }
        set
        {
            output = value;
            OnPropertyChanged(); // notify the GUI that something has changed
        }
    }

    public MainWindow()
    {
        this.DataContext = this;
        InitializeComponent();
        this.Loaded += MainWindow_Loaded;
    }

    private void MainWindow_Loaded(object sender, RoutedEventArgs e)
    {
        Output = "Hallo";
    }

    public event PropertyChangedEventHandler PropertyChanged;
    protected void OnPropertyChanged([CallerMemberName] string propertyName = "")
    {
        if (PropertyChanged != null) {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName: propertyName));
        }
    }
}

XAML 代码如下所示:

&lt;TextBox Text="{Binding Output}"/&gt;

如您所见,每当Output 属性更改时,都会调用PropertyChanged 事件。绑定到该属性的每个 GUI 元素都会知道发生了一些变化。

注意:[CallerMemberName] 自动获取调用该方法的属性的名称。如果您不想使用它,请将其删除。不过,您必须将 OnPropertyChanged 调用更改为 OnPropertyChanged("Output");

【讨论】:

  • 我已经实现了[AddINotifyPropertyChangedInterface] public class MainViewModel
  • @4est 你有没有将OnPropertyChanged 添加到setter 中?
  • 我正在使用 PropertyChanged.Fody,但我认为我不需要它?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-10-23
  • 1970-01-01
  • 2012-09-09
  • 1970-01-01
  • 2012-01-12
  • 2010-10-02
  • 1970-01-01
相关资源
最近更新 更多