我有这个正在运行的DocumentViewer,
Xaml代码:
<DocumentViewer Document="{Binding XpsDocument}" Loaded="documentViewer_Initialized"/>
ViewModel代码:
void Load()
{
MemoryStream ms = new MemoryStream();
Package pkg = Package.Open(ms, FileMode.Create, FileAccess.ReadWrite);
string pack = "pack://report.xps";
PackageStore.RemovePackage(new Uri(pack));
PackageStore.AddPackage(new Uri(pack), pkg);
XpsDocument doc = new XpsDocument(pkg, CompressionOption.NotCompressed, pack);
XpsSerializationManager rsm = new XpsSerializationManager(new XpsPackagingPolicy(doc), false);
DocumentPaginator paginator = ((IDocumentPaginatorSource)CreateFlowDocument()).DocumentPaginator;
ReportPaginator rp = new ReportPaginator(this, data);
rsm.SaveAsXaml(rp);
xpsDocument = doc.GetFixedDocumentSequence();
}
我想在菜单栏中添加一些按钮。我找到了一个解决方案,使它工作,但它似乎不是一个可靠的方法。
我设法找到一个类型为ToolBar且Count为10的子项,这是默认工具栏。但我对我的做法并不满意。有没有人有更好的主意?
private void documentViewer_Initialized(object sender, EventArgs e)
{
var dv = sender as DocumentViewer;
if (dv == null)
return;
var tb = FindToolbar(dv);
if (tb != null)
tb.Items.Add(new Button { Content = "askjsdfsdf"});
}
public ToolBar FindToolbar(System.Windows.FrameworkElement root)
{
ToolBar target = null;
int c = System.Windows.Media.VisualTreeHelper.GetChildrenCount(root);
for (int i = 0; i < c; i++)
{
var child = System.Windows.Media.VisualTreeHelper.GetChild(root, i) as System.Windows.FrameworkElement;
if (child == null) continue;
var menu = child as ToolBar;
if (menu != null)
if (menu.Items.Count == 10)
return menu;
target = FindToolbar(child);
if (target != null) return target;
}
return target;
}