利用WPF 的Crystal Report View 做Binding 時, 須要在其viewer control 中以method 形式進行設定. 正常情況下, WPF 於XAML 中不能直接叫用其method 更新, 故唯有透過 Behavior 進行叫用.
建立Behavior, 當Report 有修改時觸動事件, 再將更新的資料加到Control 中.
public class CrystalReportViewerBehaviour
{
public static readonly DependencyProperty ReportSourceProperty =
DependencyProperty.RegisterAttached(
"ReportSource",
typeof(object),
typeof(CrystalReportViewerBehaviour),
new PropertyMetadata(ReportSourceChanged)
);
private static void ReportSourceChanged(
DependencyObject d,
DependencyPropertyChangedEventArgs e)
{
var crviewer = d as CrystalReportsViewer;
if (crviewer != null)
{
crviewer.ViewerCore.ReportSource = e.NewValue;
crviewer.ViewerCore.Zoom(BOApp.DataSources.Constant.CRYSTAL_REPORT.ZOOM.PAGE_WIDTH);
}
}
public static void SetReportSource(DependencyObject target, object value)
{
target.SetValue(ReportSourceProperty, value);
}
public static object GetReportSource(DependencyObject target)
{
return target.GetValue(ReportSourceProperty);
}
}
叫用方法:
<UserControl xmlns:viewer="clr-namespace:SAPBusinessObjects.WPF.Viewer;assembly=SAPBusinessObjects.WPF.Viewer"
xmlns:behaviours="clr-namespace:Behaviours"
>
<viewer:CrystalReportsViewer Grid.Row="1" Grid.Column="1" Grid.RowSpan="2"
behaviours:CrystalReportViewerBehaviour.ReportSource="{Binding Path=DataContext.ChequeReceiptReport, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=FrameworkElement}, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
ShowCopyButton="False" ShowExportButton="False" ShowLogo="False" ShowOpenFileButton="False" ShowPrintButton="False" ShowSearchTextButton="False" ShowToggleSidePanelButton="False" ShowRefreshButton="False"
ToggleSidePanel="None"
/>
</UserControl>
而於View Model 中使用方法如下:
private void ReloadReportDocument()
{
if (ChequeReceiptReport != null)
ChequeReceiptReport.Dispose(); // Dispose file before update data source to prevent cannot load file issue.
ChequeReceiptReport = new ChequeReceiptReport();
ChequeReceiptReport.SetDataSource(SelectedChequeReceipts);
}
Leave a Reply