这可以通过MessageBox
扩展 WPF 工具包实现。它具有Text
依赖属性,可以绑定数据,但不幸的是,MessageBox
初始化是隐藏的,并且解决方案包含多行:
首先,我们需要我们的MessageBox
祖先,因为我们将调用受保护的InitializeMessageBox
方法(应用标准消息框设置)。然后,我们需要进行Show
重载,这将绑定到Text
:
class MyMessageBox : Xceed.Wpf.Toolkit.MessageBox
{
public static MessageBoxResult Show(object dataContext)
{
var messageBox = new MyMessageBox();
messageBox.InitializeMessageBox(null, null, "Hello", MessageBoxButton.OKCancel, MessageBoxImage.Question, MessageBoxResult.Cancel);
messageBox.SetBinding(MyMessageBox.TextProperty, new Binding
{
Path = new PropertyPath("Text"),
Source = dataContext
});
messageBox.ShowDialog();
return messageBox.MessageBoxResult;
}
}
接下来,我们需要一个数据上下文:
sealed class MyDataContext : INotifyPropertyChanged
{
public string Text
{
get { return text; }
set
{
if (text != value)
{
text = value;
OnPropertyChanged("Text");
}
}
}
private string text;
private void OnPropertyChanged(string propertyName)
{
var handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
还有一个代码,它将更改消息框中的文本:
public partial class MainWindow : Window
{
private readonly MyDataContext dataContext;
private readonly DispatcherTimer timer;
private int secondsElapsed;
public MainWindow()
{
InitializeComponent();
dataContext = new MyDataContext();
timer = new DispatcherTimer(TimeSpan.FromSeconds(1), DispatcherPriority.ApplicationIdle,
TimerElapsed, Dispatcher.CurrentDispatcher);
}
private void Button_Click(object sender, RoutedEventArgs e)
{
secondsElapsed = 0;
timer.Start();
MyMessageBox.Show(dataContext);
timer.Stop();
}
private void TimerElapsed(object sender, EventArgs e)
{
dataContext.Text = string.Format("Elapsed {0} seconds.", secondsElapsed++);
}
}
这种方法的好处是您不需要编写另一个消息框。