从用户控件呈现WPF LiveChart



我正在尝试从用户控件渲染笛卡尔图。文本块只是显示得很好,但不幸的是图表没有显示。我不知道如何解决这个问题。有人能给我一个提示吗?

这是用于渲染图形并将其另存为pngfile的函数。

public void ConvertGraph(Object dataContext)
{
UserControl ucGraph = new Graph
{
DataContext = dataContext
};
ucGraph.Measure(new Size(400, 400));
ucGraph.Arrange(new Rect(new Size(400, 400)));
ucGraph.UpdateLayout();
RenderTargetBitmap bmp = new RenderTargetBitmap(400, 400, 96, 96, PixelFormats.Pbgra32);

bmp.Render(ucGraph);
var encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(bmp));
using (Stream stm = File.Create(@"c:Temptest.png"))
encoder.Save(stm);
}

这是UserControl。

<UserControl x:Class="LogAnalyzerWpf.Views.PrintViews.Graph"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
xmlns:local="clr-namespace:LogAnalyzerWpf.Views.PrintViews"
xmlns:vm="clr-namespace:LogAnalyzerWpf.ViewModels"
xmlns:lvc="clr-namespace:LiveCharts.Wpf;assembly=LiveCharts.Wpf"
mc:Ignorable="d" 
d:DesignHeight="450" d:DesignWidth="800"
Background="White">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="20"/>
<RowDefinition/>
</Grid.RowDefinitions>
<TextBlock Grid.Row="0" Text="{Binding HighLevelAlarm}"></TextBlock>

<lvc:CartesianChart DisableAnimations="True" Grid.Column="0" Grid.Row="1" LegendLocation="Bottom" Series="{Binding seriesCollection}">
<lvc:CartesianChart.AxisX>
<lvc:Axis Title="Date" Labels="{Binding DateTimeValues}"></lvc:Axis>
</lvc:CartesianChart.AxisX>
<lvc:CartesianChart.AxisY>
<lvc:Axis Title="Temperature (°C)"/>
<lvc:Axis Title="Level (mm)" Position="RightTop" />
</lvc:CartesianChart.AxisY>
</lvc:CartesianChart>
</Grid>
</UserControl>

我做了一些更改,使它开始工作。

  1. ConvertGraph方法中,将UserControl ucGraph = new Graph更改为Graph ucGraph = new Graph
  2. 在xaml中,给lvc:CartesianChart取一个类似x:Name="chart"的名称
  3. ConvertGraph方法中,在调用ucGraph.UpdateLayout()之前,也要调用ucGraph.chart.Update(true,true);,这将强制它重新绘制自己

此处概述的说明:https://github.com/Live-Charts/Live-Charts/blob/develop/Examples/Wpf/CartesianChart/Chart%20to%20Image/ChartToImageSample.xaml.cs

顺便说一句,我还建议将图表上的DisableAnimations设置为true,这样在保存时就不会干扰渲染(如果图表很复杂,这可能很重要(。

相关内容

  • 没有找到相关文章

最新更新