以下是我在视图模型中设置文档的代码
ReportDocument report = new ReportDocument();
report.Load("Reports/Test.rpt");
var data_ = db.Det_QualificationMaster.Where(x => x.MUA_id == 6)
.Select(x => new { x.CollageName, x.StartYear, x.EndYear
}).ToList();
report.SetDataSource(data_);
页面中的代码
<viewer:CrystalReportsViewer HorizontalAlignment="Left" Name="crystalReportsViewer1"
VerticalAlignment="Top" Height="400" Width="400" >
如何将数据从视图模型绑定到页面
答案 0 :(得分:3)
我找到了解决方案我自己想与大家分享。感谢Andre-Alves Lima博客这里的链接http://www.andrealveslima.com.br/blog/index.php/2016/07/20/utilizando-o-crystal-reports-com-mvvm-no-wpf/
它是葡萄牙语所以翻译我把代码放在
之下添加静态类 ReportSourceBehaviour.cs
public static class ReportSourceBehaviour
{
public static readonly System.Windows.DependencyProperty ReportSourceProperty =
System.Windows.DependencyProperty.RegisterAttached(
"ReportSource",
typeof(object),
typeof(ReportSourceBehaviour),
new System.Windows.PropertyMetadata(ReportSourceChanged));
private static void ReportSourceChanged(System.Windows.DependencyObject d, System.Windows.DependencyPropertyChangedEventArgs e)
{
var crviewer = d as SAPBusinessObjects.WPF.Viewer.CrystalReportsViewer;
if (crviewer != null)
{
crviewer.ViewerCore.ReportSource = e.NewValue;
}
}
public static void SetReportSource(System.Windows.DependencyObject target, object value)
{
target.SetValue(ReportSourceProperty, value);
}
public static object GetReportSource(System.Windows.DependencyObject target)
{
return target.GetValue(ReportSourceProperty);
}
}
ViewModel中的
public class MainViewModel
{
public CrystalDecisions.CrystalReports.Engine.ReportDocument Report { get; set; }
public MainViewModel()
{
Report = new NameOfRptFile();
//Add data to the report
}
}
页面中的(XAML)
<Window xmlns:Viewer="clr-namespace:SAPBusinessObjects.WPF.Viewer;assembly=SAPBusinessObjects.WPF.Viewer" x:Class="CrystalWPFMVVM.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:CrystalWPFMVVM"
Title="MainWindow" Height="350" Width="525"
DataContext="{StaticResource MainViewModel}">
<Grid>
<Viewer:CrystalReportsViewer x:Name="CrystalReportsViewer"
local:ReportSourceBehaviour.ReportSource="{Binding Path=DataContext.Report, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=FrameworkElement}}"/>
</Grid>
</Window>