Dynamically adjusting Y Axis in DevExpress XtraCharts for WinForms - winforms

In DevExpress XtraCharts for WinForms, is there a way to have the Y Axis adjust automatically as a user scrolls left and right through the data (so that the data that is currently displayed on the screen fills most of the chart)?
If not automatically are there any demos or would someone have any pointers on how to do this?
You can see this effect happening on this video as the user scrolls left and right the Y-Axis changes: https://www.youtube.com/watch?v=HmA6vANrKKk

According to DevExpress tech support, you have to do it yourself:
"It is necessary to calculate and set Axis Y range manually as described in the Auto adjust Y-Axis range when scrolling on zooming on X-Axis thread. Please try this solution and let me know if you need an additional assistance with this solution implementation."
I also had to add the following statement to get the Y-Axis changes to show up:
stockView.AxisY.VisualRange.SideMarginsValue = 0

Just set the Axis.VisualRange.Auto property to true to specify that the minimum and maximum axis values are calculated automatically based upon the series being drawn.

Maybe this helps some. The following code solves 2 issues: a) updating of yAxis on main ChartControl when zooming or scrooling, and b) updating the same when adjusting the range on an associated RangeControl.
I use a RangeControl in addition to my ChartControl and strangely the event RangeChanged of RangeControl is raised even when you zoom or scroll on the main chart. This should not be and stanger even the opposite does not hold true: When changing the range of RangeControl none of the events of ChartControl are raised. What complicates things even further is RangeChanged of RangeControl runs on a background thread.
private void RangeControlOnRangeChanged(object sender, RangeControlRangeEventArgs range)
{
var measureUnit = ((XYDiagram)chartControl.Diagram).AxisX.DateTimeScaleOptions.MeasureUnit;
var origin = default(DateTime);
DateTime minDt, maxDt;
switch (measureUnit)
{
case DateTimeMeasureUnit.Millisecond:
minDt = origin.AddMilliseconds((double) range.Range.Minimum);
maxDt = origin.AddMilliseconds((double) range.Range.Maximum);
break;
case DateTimeMeasureUnit.Second:
minDt = origin.AddSeconds((double) range.Range.Minimum);
maxDt = origin.AddSeconds((double) range.Range.Maximum);
break;
case DateTimeMeasureUnit.Minute:
minDt = origin.AddMinutes((double) range.Range.Minimum);
maxDt = origin.AddMinutes((double) range.Range.Maximum);
break;
case DateTimeMeasureUnit.Hour:
minDt = origin.AddHours((double) range.Range.Minimum);
maxDt = origin.AddHours((double) range.Range.Maximum);
break;
case DateTimeMeasureUnit.Day:
minDt = origin.AddDays((double) range.Range.Minimum);
maxDt = origin.AddDays((double) range.Range.Maximum);
break;
case DateTimeMeasureUnit.Year:
minDt = origin.AddYears((int)(double) range.Range.Minimum);
maxDt = origin.AddYears((int)(double) range.Range.Maximum);
break;
default:
throw new NotImplementedException();
}
var visibleDataPoints = DataSeries.Where(x => x.TimeStamp >= minDt && x.TimeStamp <= maxDt);
var newMinValue = visibleDataPoints.Min(x => x.Value);
var newMaxValue = visibleDataPoints.Max(x => x.Value);
chartControl.BeginInvoke(new Action(() => ((XYDiagram)chartControl.Diagram).AxisY.VisualRange.SetMinMaxValues(newMinValue, newMaxValue)));
}
Note that DataSeries here is a collection that implements IList, where DataPoint is struct that holds a DateTime time stamp and a value of type double. But the binding can be done in a myriads of ways. Also note that here you don't even need to hook up Scroll or Zoom events because of the above mentioned oddity in that the RangeChanged event of RangeControl is raised when you scroll or zoom.
I find some of the design and some lacking core features of the DevExpress WinForms charting library extremely embarrassing, given they allow for the most detailed little items to be adjusted while some hugely important features are missing and/or still have not been fixed/added years after they were brought up by users. Maybe I am the only one to complain but I felt it should be voiced.

Try below codeļ¼š
diagram.DependentAxesYRange = DefaultBoolean.True;
diagram.AxisY.WholeRange.AlwaysShowZeroLevel = false;

Related

Windows Form Label position issue

I have a UserControl which has a Label at the bottom right corner defined as followed:
this.lblInspectionName.AutoSize = true;
this.lblInspectionName.Font = new System.Drawing.Font("Segoe UI", 10.25F, System.Drawing.FontStyle.Bold);
this.lblInspectionName.Location = new System.Drawing.Point(3, 7);
this.lblInspectionName.Name = "lblInspectionName";
this.lblInspectionName.Size = new System.Drawing.Size(113, 19);
this.lblInspectionName.TabIndex = 0;
this.lblInspectionName.Text = "___";
Its Text content changes based on other events. The problem is that when the Label gets bigger, it goes to left (as I want otherwise it exceeds the right border), but when it gets smaller again the location is the same as the previous case and it's positioned too left.
Do you know how I can let the label grows to left when necessary keeping always a certain distance/margin to the right border? Thanks in advance!
EDIT
Doing as suggested, the situation is the following:
I would add these properties settings
this.lblInspectionName.Dock = DockStyle.Bottom;
this.lblInspectionName.TextAlign = ContentAlignment.BottomRight;
But you need to set the AutoSize back to false.
// Comment out this line. False is default
// this.lblInspectionName.AutoSize = true;

Exporting TeeChart as Image

We are using TeeChart for .net (Version 4.1.2013.7302) in our forms application.
One of the charts in our product has Y Axis scrolling enabled. This makes some portion of chart visible at a given instance. To see other part of chart, user needs to use the scrollbar. A separate scrollbar is used instead of axis scrollbar, as there will be a adjoining grid control and; both chart & grid are expected to be scrolled using common scrollbar. Following is the sample form image depicting the scenario:
We are using TeeChart's export functionality to export this chart as an image. But since chart has scrolling enabled (i.e. minimum of chart is not visible by default); TeeChart is exporting only visible portion of Chart, and not the entire chart. Following is the image of chart exported:
Please suggest if there exists any way to export the entire chart as an image, and not just the visible portion of it?
Thanks in Advance.
Here's a fuller version of Yeray's code that fills out the exported image to the size of the full, mainly non-visible chart:
private void button11_Click(object sender, EventArgs e)
{
//get zoomed axis min maxes
double xtmpMin = tChart1.Axes.Bottom.Minimum;
double xtmpMax = tChart1.Axes.Bottom.Maximum;
double ytmpMin = tChart1.Axes.Left.Minimum;
double ytmpMax = tChart1.Axes.Left.Maximum;
//how many pixels are plotted for the axes' ranges
int yPixelRange = tChart1.Axes.Left.CalcPosValue(tChart1.Axes.Left.Minimum)-tChart1.Axes.Left.CalcPosValue(tChart1.Axes.Left.Maximum);
int xPixelRange = tChart1.Axes.Bottom.CalcPosValue(tChart1.Axes.Bottom.Maximum) - tChart1.Axes.Bottom.CalcPosValue(tChart1.Axes.Bottom.Minimum);
//get the chart header/footer space to re-apply to chart
int yMargins = tChart1.Bounds.Height - yPixelRange;
int xMargins = tChart1.Bounds.Width - xPixelRange;
//how many pixels are we getting per axis scale
double pixelsPerYAxisInt = yPixelRange / (ytmpMax - ytmpMin);
double pixelsPerXAxisInt = xPixelRange / (xtmpMax - xtmpMin);
//what increment are we at. Note. To get this back we may need to mod font size, min separation
double yInc = tChart1.Axes.Left.CalcIncrement;
double xInc = tChart1.Axes.Bottom.CalcIncrement;
//now reset auto axes before plotting full chart. Could use other criteria here
tChart1.Axes.Left.Automatic = true;
tChart1.Axes.Bottom.Automatic = true;
//Repaint full Chart (necessary for positioning calcs)
tChart1.Draw();
//set increments on full scales (note Chart will try to set them,
//but if it can't you have the last word with label separation, font size, etc)
tChart1.Axes.Left.Increment = yInc;
tChart1.Axes.Bottom.Increment = xInc;
//dimension chart for export
double fullYRange = tChart1.Axes.Left.Maximum - tChart1.Axes.Left.Minimum;
double fullXRange = tChart1.Axes.Bottom.Maximum - tChart1.Axes.Bottom.Minimum;
int fullYSize = (int)((pixelsPerYAxisInt * fullYRange) + yMargins);
int fullXSize = (int)((pixelsPerXAxisInt * fullXRange) + xMargins);
//setup and export image
tChart1.Export.Image.PNG.Width = fullXSize;
tChart1.Export.Image.PNG.Height = fullYSize;
tChart1.Export.Image.PNG.Save(#"c:\mypath\chart.png");
//reset screen chart to where it was
tChart1.Axes.Bottom.SetMinMax(xtmpMin, xtmpMax);
tChart1.Axes.Left.SetMinMax(ytmpMin, ytmpMax);
}
There are many ways to optimise that code, Axis does have an iRange that I haven't tried, and some of the steps can be brought together but I hope they are clear and useful and give you something of what you're looking for.
You can manually adjust your axis scale, export your chart and then restore your axis. Ie (if 0 - 4.25 in the bottom axis is the "entire chart"):
double tmpMin = tChart1.Axes.Bottom.Minimum;
double tmpMax = tChart1.Axes.Bottom.Maximum;
tChart1.Axes.Bottom.SetMinMax(0, 4.25);
tChart1.Export.Image.JPEG.Save(myFileName);
tChart1.Axes.Bottom.SetMinMax(tmpMin, tmpMax);

Scroll to selection in Angular ui-grid (not ng-grid)

For my Angular JS grid work, I'm using ui-grid rather than ng-grid as ui-grid is meant to be the new version which is purer Angular.
I've got a grid that I'm populating with a http response, and I'm able to select a row (based on finding the record matching a $scope variable value) using the api.selection.selectRow method call.
What I need to do next is scroll the grid to that record.
There's an existing stack overflow question along the same lines that is for ng-grid and the answer to that refers to undocumented features which are not present in ui-grid so I can't use that approach.
The closest I've got is finding $scope.gridApi.grid to get a reference to the actual grid itself but looking through the properties and methods in the Chrome debugger doesn't show anything that sounds like it could work.
You can use the cellNav plugin. You should already have a reference to your row entity from the selection. The documentation is here.
gridApi.cellNav.scrollTo(grid, $scope, rowEntity, null);
I managed to hack together something that works pretty well but it's a bit dodgy and could probably be cleaner with a bit more Angular/jquery understanding.
I used the browser dom explorer to find that the scrollbars have a css class that we can detect to find them and then set the scroll properties on them to have the grid scroll (the grid and scrollbars are separate divs but their properties are bound so changing one updates the other).
It doesn't completely work for scrolling to the last row of the grid. This could be a timing issue, I've noticed when using breakpoints that the grid comes on screen a little larger and then shrinks down to it's final size. This could be messing with the scrolling values.
The first loop finds the height of the grid by adding up the rows, and the y position of the row for my data object (project), then we find the scrollbar and set it's scrollTop, trying to centre the row on screen without going out of bounds.
var grid = $scope.projectsGridApi.grid;
// var row = grid.rowHashMap.get(project.$$hashKey);
var found = false;
var y = 0;
var totalY = 0;
var rowHeight = 0;
for (var rowIdx in grid.rows)
{
var row = grid.rows[rowIdx];
if (row.entity.$$hashKey == project.$$hashKey)
{
found = true;
rowHeight = row.height;
}
if (!found)
{
y += row.height;
}
totalY += row.height;
}
// now find the scroll bar div and set it's scroll-top
// (todo: checking if we're at the end of the list - setting scrollTop > max means it doesn't work properly
var grid = $scope.projectsGridApi.grid;
// annoyingly this is nastily coded to find the scrollbar and isn't completely right
// I think the grid is a little taller when this is called, then shrinks
// which affects what the maximum is (so we might not always be able to put the selected item on screen if it is the last one).
var holderDiv = $('#projectsGridHolder');
if (holderDiv)
{
var scrollBarDivs = holderDiv.find('.ui-grid-native-scrollbar');
if (scrollBarDivs)
{
for (var scrollBarDivIdx in scrollBarDivs)
{
var scrollBarDiv = scrollBarDivs[scrollBarDivIdx];
var scrollBarDivClass = scrollBarDiv.className;
if (scrollBarDivClass)
{
if (scrollBarDivClass.indexOf('vertical') != -1)
{
var scrollHeight = scrollBarDiv.scrollHeight;
var clientHeight = scrollBarDiv.clientHeight;
if (rowHeight > 0)
{
y -= (clientHeight - rowHeight) / 2; // center on screen be scrolling slightly higher up
}
if (y < 0) y = 0;
else if (y > totalY - clientHeight) y = totalY - clientHeight;
scrollBarDiv.scrollTop = y;
}
}
}
}
}

WPF - How to work out how much of a canvas background image is cropped?

I have a canvas with a background image:
var bi = new BitmapImage(new Uri(imgLocFull));
var ib = new ImageBrush(bi) {Stretch = Stretch.UniformToFill};
MyCanvas.Background = ib;
I am overlaying various shapes on the image, and want the position of the shapes relative to the background image to be fixed.
If my application window is resized, the amount of the image that is cropped, horizontally and vertically, changes, and when my shapes are redrawn, they do not appear in the same position on the background image.
How can I determine how much of the image has been cropped (to apply an adjustment factor to the overlaid objects' positions?) Or is there a better way of fixing the location of a shape relative to the background image?
Here is my present drawing code:
var l = new Ellipse();
var scb = new SolidColorBrush();
scb.Color = Color.FromRgb(rCol, gCol, bCol);
l.Fill = scb;
l.StrokeThickness = 0;
l.Width = 3;
l.Height = 3;
Canvas.SetBottom(l, point.Y); // * clipping factor here?
Canvas.SetLeft(l, point.X); // * clipping factor here?
MyCanvas.Children.Add(l);
EDIT: Further Clarification
Here's a concrete example of what I am trying to achieve. My image is an aerial photograph, and I want to mark a particular geographical feature (with, say, an ellipse.)
When the window is resized, the ellipse doesn't stay on the feature, it stays relative to the left and top of the canvas.
I can get it closer to the right place by moving it using a factor (newx = newheight/oldheight * oldx) but this doesn't quite work because of the UniformToFill stretch mode, which sees some of the image clipped off the canvas.
The Top and Left of the Canvas are 'anchored', while the Bottom and Right move when resizing... try setting the Canvas.Top Attached Property instead, along with the Canvas.Left Attached Property as you are:
var l = new Ellipse();
var scb = new SolidColorBrush();
scb.Color = Color.FromRgb(rCol, gCol, bCol);
l.Fill = scb;
l.StrokeThickness = 0;
l.Width = 3;
l.Height = 3;
Canvas.SetTop(l, point.Y); // * clipping factor here?
Canvas.SetLeft(l, point.X); // * clipping factor here?
MyCanvas.Children.Add(l);
UPDATE >>>
You asked Or is there a better way of fixing the location of a shape relative to the background image?
I answered this question, so I don't understand why you would need to do anything else... your objects will not move when the screen in resized *if you only set the Grid.Top and Grid.Left properties.

WPF FlowDocument: force calculation of height etc. "off screen"

My target: a DocumentPaginator which takes a FlowDocument with a table, which splits the table to fit the pagesize and repeat the header/footer (special tagged TableRowGroups) on every page.
For splitting the table I have to know the heights of its rows.
While building the FlowDocument-table by code, the height/width of the TableRows are 0 (of course). If I assign this document to a FlowDocumentScrollViewer (PageSize is set), the heights etc. are calculated. Is this possible without using an UI-bound object? Instantiating a FlowDocumentScrollViewer which is not bound to a window doesn't force the pagination/calculation of the heights.
This is how I determine the height of a TableRow (which works perfectly for documents shown by a FlowDocumentScrollViewer):
FlowDocument doc = BuildNewDocument();
// what is the scrollviewer doing with the FlowDocument?
FlowDocumentScrollViewer dv = new FlowDocumentScrollViewer();
dv.Document = doc;
dv.Arrange(new Rect(0, 0, 0, 0));
TableRowGroup dataRows = null;
foreach (Block b in doc.Blocks)
{
if (b is Table)
{
Table t = b as Table;
foreach (TableRowGroup g in t.RowGroups)
{
if ((g.Tag is String) && ((String)g.Tag == "dataRows"))
{
dataRows = g;
break;
}
}
}
if (dataRows != null)
break;
}
if (dataRows != null)
{
foreach (TableRow r in dataRows.Rows)
{
double maxCellHeight = 0.0;
foreach (TableCell c in r.Cells)
{
Rect start = c.ElementStart.GetCharacterRect(LogicalDirection.Forward);
Rect end = c.ElementEnd.GetNextInsertionPosition(LogicalDirection.Backward).GetCharacterRect(LogicalDirection.Forward);
double cellHeight = end.Bottom - start.Top;
if (cellHeight > maxCellHeight)
maxCellHeight = cellHeight;
}
System.Diagnostics.Trace.WriteLine("row " + dataRows.Rows.IndexOf(r) + " = " + maxCellHeight);
}
}
Edit:
I added the FlowDocumentScrollViewer to my example. The call of "Arrange" forces the FlowDocument to calculate its heights etc. I would like to know, what the FlowDocumentScrollViewer is doing with the FlowDocument, so I can do it without the UIElement. Is it possible?
My guess would be no, you can't do it without a UIElement.
FlowDocument, by itself, doesn't actually render anything. Looking at the type in relector it looks like it is just a data type. Its about like having a string and wanting to know its size when rendered ... can't really do it without doing some kind of measure pass.
I don't know for sure, but you might get better performance in the arrange pass by passing in Double.PositiveInfinity for the size rather than 0. At least then it won't have to worry about measuring 'n' line breaks.

Resources