I have a WPF MMVM application and we are getting xml parser exception from viewmodel method. But the problem is I don't want to show the exception from viewmodel. I would like to show the message from view ( CustomMessageBox.Show()
call from view)
As per the below code, I am calling CustomMessageBox.Show()
from view model catch block. How can I call CustomMessageBox.Show()
from xaml.cs
or xaml
?
How can we notify the view about this and call CustomMessageBox.Showfrom
view?. This code snippet is called in a WPF command.
Current implementation:
try
{
var xamlReader = XamlReader.Parse(xamlText);
var gb = modelTemplate.GetGraphicalObject("Icons");
var strings = new Dictionary<string, string> { { "Default", xamlText } };
gb.UpdateGraphicalObject(strings, null, null);
if (xamlReader != null)
{
var view = new Viewbox();
view.Child = (UIElement)xamlReader;
view.Stretch = Stretch.Uniform;
modelVM.Icon = view;
}
}
catch (XamlParseException)
{
CustomMessageBox.Show("Invalid XAML file specified.", Properties.Resources.NextGenSim, MessageBoxButton.OK, MessageBoxImage.Error);
//throw new XamlParseException("Invalid XAML file specified");
}
If you're using a messenger / event aggregator (eg MVVM Light), you can send a message containing the exceptions details from the viewmodel to the view, which, when received, can trigger the message box to show.
Using MVVM Light , it might look like the following:
Viewmodel:
Messenger.Default.Send(new ErrorMessage("Invalid XAML file specified.",
Properties.Resources.NextGenSim));
View
Messenger.Default.Register<ErrorMessage>(this, message =>
{
CustomMessageBox.Show(message.Message, message.Details,
MessageBoxButton.OK, MessageBoxImage.Error);
}
The ErrorMessage is a custom class, containing whatever details about the exception you need to display to the user.
您可以使用ValueConverter
创建一个具有可视性绑定到ViewModel属性ErrorMessage
的模式Popup
ValueConverter
,当给定的源不为null或为空时,该方法将返回true。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.