使用C更新wpf中状态栏中的文本#
我想在wpf的状态栏中更新一个文本框 我在列表框中有一个文件列表。在每个文件上,我将通过调用say方法ProcessFile()来执行一些操作。因此,每当文件处理完成时,我都希望在状态栏文本中显示该文件的名称 我试过这样的方法:使用C更新wpf中状态栏中的文本#,wpf,statusbar,Wpf,Statusbar,我想在wpf的状态栏中更新一个文本框 我在列表框中有一个文件列表。在每个文件上,我将通过调用say方法ProcessFile()来执行一些操作。因此,每当文件处理完成时,我都希望在状态栏文本中显示该文件的名称 我试过这样的方法: private void button_Click(object sender, RoutedEventArgs e) { statusBar.Visibility = Visibility.Visible;
private void button_Click(object sender, RoutedEventArgs e)
{
statusBar.Visibility = Visibility.Visible;
DispatcherFrame frame = new DispatcherFrame();
Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Background, new DispatcherOperationCallback(TimeConsumingMethod), frame);
Dispatcher.PushFrame(frame);
statusBar.Visibility = Visibility.Collapsed;
}
public object TimeConsumingMethod(Object arg)
{
((DispatcherFrame)arg).Continue = false;
foreach (string fileName in destinationFilesList.Items)
{
txtStatus.Text = fileName.ToString();
//Assume that each process takes some time to complete
System.Threading.Thread.Sleep(1000);
}
return null;
}
但我只能在状态栏中看到最后一个文件的名称。代码怎么了?如何更正它?当您使用ViewModel时,我会在ViewModel中定义一个属性“ProcessedFile”,并将状态栏的文本框绑定到该属性 每次处理文件时,我都会将属性“ProcessedFile”设置为文件名 下面是ViewModel的一些代码
public class ViewModel : INotifyPropertyChanged {
private string _processedFile;
public string ProcessedFile {
get {
return _processedFile;
}
set {
if (_processedFile != value) {
_processedFile = value;
if (PropertyChanged != null) {
PropertyChanged(this, new PropertyChangedEventArgs("ProcessedFile"));
}
}
}
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
#endregion
public void ProcessFile() {
// Process the file
ProcessedFile = //Set the Property to the processed file
}
}
下面是将文本框绑定到属性的XAML。(我假设ViewModel被设置为文本框的DataContext)
有更多的方法可以做到这一点 直接从代码设置内容
您需要指定
文本框的名称,以便访问其内容:
XAML
使用数据绑定
您需要创建一些对象,并将其设置为DataContext
到TextBox
或包含该文本框(状态栏、窗口等)的某些WPF元素
XAML:
有关数据绑定的更多信息,请参见如果只能使用Dispatcher使用几行代码创建Sperate类,为什么要创建它?有关说明,请参见“数据绑定概述”一文。链接在答案的末尾。
<TextBox Text="{Binding ProcessedFile, Mode=OneWay}"/>
<TextBox x:Name="myTextBox" />
...
ProcessFile(someFileName);
myTextBox.Text = someFileName;
<TextBox Text="{Binding Path=ProcessedFileName}" />
public MyClass : INotifyPropertyChanged
{
public string ProcessedFileName {get; set;}
public void ProcessFile(string someFileName)
{
// Processing file code here
// When done processing, set file name to property
ProcessedFileName = someFileName;
OnPropertyChanged("ProcessedFileName");
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}