在我的MainViewModel.中,我有一个将其属性Document绑定到MainWindow中的FlowDocument的FlowDocumentScrollViewer
此文档是从远程计算机上的外部xaml文件存储加载的。目前,我能够通过XamlReader.Load(xamlfile)正确地加载这个文档,并在FlowDocumentScrollViewer中显示它。到目前一切尚好。
当我试图在此文档中添加超链接时,会出现此问题。因为要处理RequestNavigate事件,我需要一个x:Class。目前,这个类需要成为我的MainWindow,因为事件是在代码隐藏中处理的。显然,当我在我的外部文档中添加x:Class="Ugrader.MainWindow"时,我在解析时得到了一个可爱的'System.Windows.Markup.XamlParseException'。
有办法解决这个问题吗?
这是我的代码
MainWindow.xaml
<Window x:Class="Ugrader.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Geco3-Upgrading version"
WindowStyle="none" ResizeMode="NoResize" ShowInTaskbar="False" WindowStartupLocation="CenterScreen"
Height="400" Width="700"
DataContext="{Binding Main,Source={StaticResource Locator}}">
<FlowDocumentScrollViewer Grid.Column="1" Background="{x:Null}" VerticalScrollBarVisibility="Hidden"
Document="{Binding WhatsNewDoc}"/>
</Window>MainViewModel.cs
namespace Ugrader.ViewModel
{
public class MainViewModel : ViewModelBase
{
#region Constructor
public MainViewModel()
{
try
{
FileStream xamlFile = new FileStream(updateLocation + "whatsnew.xaml", FileMode.Open, FileAccess.Read);
FlowDocument current = System.Windows.Markup.XamlReader.Load(xamlFile) as FlowDocument;
WhatsNewDoc = current;
}
catch (Exception)
{
}
}
#endregion
#region Properties
private FlowDocument _watsNewDoc = new FlowDocument();
public FlowDocument WhatsNewDoc
{
get
{
return _watsNewDoc;
}
set
{
if(_watsNewDoc != value)
{
_watsNewDoc = value;
RaisePropertyChanged("WhatsNewDoc");
}
}
}
#endregion
}
}外部FlowDocument
<FlowDocument x:Class="Ugrader.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
ColumnWidth="400" FontSize="12" FontFamily="Century Gothic" Foreground="LightGray">
<Paragraph>
<Italic>
For additionnal information, please watch this
<Hyperlink TextDecorations="{x:Null}" RequestNavigate="Hyperlink_Clicked" NavigateUri="path_to_the_file" >video</Hyperlink>
</Italic>
</Paragraph>
</FlowDocument>顺便问一下,是否有一种方法来处理这个解析异常(如果外部文件不好),因为即使在这个try/catch块中,这个停止了我的程序。
提前谢谢你,
巴斯蒂安。
发布于 2014-06-12 11:42:43
我找到了一种方法来解决我的问题,它不是真的很漂亮,不尊重mvvm的精神,但是,这是有效的。
因此,由于不可能在运行时添加x:Class (我猜),所以我开始在运行时中处理每个Hyperlink的RequestNavigate事件。所以解决方案很简单(而且很脏)。
在代码隐藏中(是的,我知道,它很难看),在MainWindow加载事件上,我在文档中找到所有超链接,并处理每个RequestNavigate事件。就像这样简单(肮脏)。
以下是一些代码:
private void Window_Loaded(object sender, RoutedEventArgs e)
{
var hyperlinks = GetVisuals(this).OfType<Hyperlink>();
foreach (var link in hyperlinks)
link.RequestNavigate += link_RequestNavigate;
}
public static IEnumerable<DependencyObject> GetVisuals(DependencyObject root)
{
foreach (var child in LogicalTreeHelper.GetChildren(root).OfType<DependencyObject>())
{
yield return child;
foreach (var descendants in GetVisuals(child))
yield return descendants;
}
}如果有人有更好的解决办法,我就接受。
https://stackoverflow.com/questions/24180103
复制相似问题