gpt4 book ai didi

c# - 如何在 MVVM 模式 WPF 应用程序中的 View 模型中设置 Crystal Report 中的数据源

转载 作者:行者123 更新时间:2023-12-03 10:57:17 25 4
gpt4 key购买 nike

下面是我在 View 模型中设置文档的代码

    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" >

如何将数据从 View 模型绑定(bind)到页面

最佳答案

我自己找到了解决方案,我想与大家分享。非常感谢 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);
}
}

在 View 模型中
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>

关于c# - 如何在 MVVM 模式 WPF 应用程序中的 View 模型中设置 Crystal Report 中的数据源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45831214/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com