Scaling InkCanvas strokes to fit specific dimensions to crop out unused space - wpf

I am attempting to scale an InkCanvas's contents (Strokes) to fit a fixed page size for printing. I want to essentially crop out all of the surrounding whitespace from the InkCanvas, and scale up the Strokes to fit the page while maintaining aspect ratio.
In the handler below the markup, you can see that I am changing the dimensions of the grid that starts at 800x300, and I'm making it 425x550, half of the size of a printable page.
markup:
<Grid>
<Button Height="100" Width="100" HorizontalAlignment="Left" PreviewMouseLeftButtonDown="Button_PreviewMouseLeftButtonDown_1" />
<Grid Width="1200" Height="1400" Background="Aquamarine" HorizontalAlignment="Right" VerticalAlignment="Top">
<Grid Background="Red" x:Name="grid" Width="800" Height="300">
<Viewbox x:Name="vb" Width="800" Height="300" Stretch="Fill" StretchDirection="Both">
<InkCanvas Width="500" Height="500" Background="Transparent" IsEnabled="True"/>
</Viewbox>
</Grid >
</Grid>
</Grid>
codebehind file:
bool b = true;
private void Button_PreviewMouseLeftButtonDown_1(object sender, MouseButtonEventArgs e)
{
if (b)
{
//I toyed with using Uniform, UniformToFill, and Fill
vb.Stretch = Stretch.Fill;
grid.Width = 425;
grid.Height = 550;
//scale viewbox down until it fits horizontally
var scaleX = grid.Width / vb.Width;
vb.Width *= scaleX;
vb.Height *= scaleX;
//if constraining it to the width made it larger than it needed to be vertically, scale it down
if (vb.Height > grid.Height)
{
var scaleY = grid.Height / vb.Height;
vb.Width *= scaleY;
vb.Height *= scaleY;
}
b = false;
}
else
{
//reset it back to what it was
vb.Stretch = Stretch.Fill;
grid.Width = 800;
grid.Height = 300;
vb.Width = grid.Width;
vb.Height = grid.Height;
b = true;
}

Related

Set Min and Max height of items in ItemsControl

I am using an ItemsControl to display a list of 1 - 10 items (usually 2 - 4). I am trying to satisfy all these requirements:
All rows must be the same height
All rows should be displayed at a height of 300 maximum if possible.
If there is not enough room to display all rows at 300 high, then display at the largest possible height.
If the largest possible height is less than 150, then display at maxsize and use a scrollbar
If the rows do not fill the page, then it must be vertically aligned at the top
This is what I have so far:
<Window x:Class="TestGridRows.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:vm="clr-namespace:TestGridRows"
mc:Ignorable="d"
d:DataContext="{d:DesignInstance vm:MainViewModel}"
Height="570" Width="800">
<ScrollViewer VerticalScrollBarVisibility="Auto">
<ItemsControl ItemsSource="{Binding Path=DataItems}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Border MinHeight="150" MaxHeight="300" BorderBrush="DarkGray" BorderThickness="1" Margin="5">
<TextBlock Text="{Binding Path=TheNameToDisplay}" VerticalAlignment="Center" HorizontalAlignment="Center" />
</Border>
</DataTemplate>
</ItemsControl.ItemTemplate>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<UniformGrid Columns="1" IsItemsHost="True" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
</ScrollViewer>
</Window>
This is what it currently looks like with 1 item:
and this is what it should look like:
2 or 3 items display as expected:
For 4+ items, the scrollbar appears correctly but the items are all sized to 150, rather than 300:
Question
How do I align the content to top when there is only 1 item? (without breaking the other functionality obviously)
Bonus question: How do I get the items to resize to maxheight instead of minheight when there are 4+ items?
During the WPF layout process, measuring and arranging will be done in order. In most cast, if an UIElement has variable size, it will return minimum required as result. But if any layout alignment has been set to Stretch, UIElement will take as possible as it can in that direction in arranging. In your case, UniFormGrid will always return 160(which is Border.MinHeight + Border.Margin.Top + Border.Margin.Bottom) * the count of items as desired height in measuring result(which will stored in DesiredSize.DesiredSize.Height). But it will take ItemsControl.ActualHeight as arranged height since it has Stretch VerticalAlignment. So, if UniFormGrid.DesiredSize.Height was less then ItemsControl.ActualHeight, UniFormGrid and any child has Stretch VerticalAlignment will be stretch in vertically, until it encountered its MaxHeight. This is why your 1 item test resulted in the center. If you change UniFormGrid.VerticalAlignment or Border.VerticalAlignment to Top, you will get a 160 height item in the top of ItemsContorl.
The most simple solution to both questions is override the measuring result base on maximum row height and minimum row height. I write the codes in below and had done some basic tests, it seems to work just fine.
namespace WpfApp1
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
}
public class MyScrollViewer : ScrollViewer
{
public double DesiredViewportHeight;
public MyScrollViewer() : base() { }
protected override Size MeasureOverride(Size constraint)
{
// record viewport's height for late calculation
DesiredViewportHeight = constraint.Height;
var result = base.MeasureOverride(constraint);
// make sure that `ComputedVerticalScrollBarVisibility` will get correct value
if (ComputedVerticalScrollBarVisibility == Visibility.Visible && ExtentHeight <= ViewportHeight)
result = base.MeasureOverride(constraint);
return result;
}
}
public class MyUniformGrid : UniformGrid
{
private MyScrollViewer hostSV;
private ItemsControl hostIC;
public MyUniFormGrid() : base() { }
public double MaxRowHeight { get; set; }
public double MinRowHeight { get; set; }
protected override Size MeasureOverride(Size constraint)
{
if (hostSV == null)
{
hostSV = VisualTreeHelperEx.GetAncestor<MyScrollViewer>(this);
hostSV.SizeChanged += (s, e) =>
{
if (e.HeightChanged)
{
// need to redo layout pass after the height of host had changed.
this.InvalidateMeasure();
}
};
}
if (hostIC == null)
hostIC = VisualTreeHelperEx.GetAncestor<ItemsControl>(this);
var viewportHeight = hostSV.DesiredViewportHeight;
var rows = hostIC.Items.Count;
var rowHeight = viewportHeight / rows;
double desiredHeight = 0;
// calculate the correct height
if (rowHeight > MaxRowHeight || rowHeight < MinRowHeight)
desiredHeight = MaxRowHeight * rows;
else
desiredHeight = viewportHeight;
var result = base.MeasureOverride(constraint);
return new Size(result.Width, desiredHeight);
}
}
public class VisualTreeHelperEx
{
public static T GetAncestor<T>(DependencyObject reference, int level = 1) where T : DependencyObject
{
if (level < 1)
throw new ArgumentOutOfRangeException(nameof(level));
return GetAncestorInternal<T>(reference, level);
}
private static T GetAncestorInternal<T>(DependencyObject reference, int level) where T : DependencyObject
{
var parent = VisualTreeHelper.GetParent(reference);
if (parent == null)
return null;
if (parent is T && --level == 0)
return (T)parent;
return GetAncestorInternal<T>(parent, level);
}
}
}
Xaml
<Window x:Class="WpfApp1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp1"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
mc:Ignorable="d"
Height="570" Width="800">
<local:MyScrollViewer VerticalScrollBarVisibility="Auto">
<ItemsControl>
<sys:String>aaa</sys:String>
<sys:String>aaa</sys:String>
<sys:String>aaa</sys:String>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Border BorderBrush="DarkGray" BorderThickness="1" Margin="5">
<TextBlock Text="{Binding ActualHeight, RelativeSource={RelativeSource AncestorType=ContentPresenter}}"
VerticalAlignment="Center" HorizontalAlignment="Center" />
</Border>
</DataTemplate>
</ItemsControl.ItemTemplate>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<local:MyUniformGrid Columns="1" MinRowHeight="150" MaxRowHeight="300" VerticalAlignment="Top"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
</local:MyScrollViewer>
</Window>

WPF DataGrid Zoom to mouse position

I have a DataGrid that LayoutTransform is Binded to a Slider like that:
<DataGrid.LayoutTransform>
<ScaleTransform
ScaleX="{Binding ElementName=MySlider, Path=Value}"
ScaleY="{Binding ElementName=MySlider, Path=Value}" />
</DataGrid.LayoutTransform>
</DataGrid>
<Slider x:Name="MySlider"
Minimum="0.3"
Maximum="2.0"
SmallChange="0.1"
LargeChange="0.1"
Value="1.0"
IsSnapToTickEnabled="True"
TickFrequency="0.1"
TickPlacement="TopLeft"
VerticalAlignment="Bottom"
HorizontalAlignment="Right"
Width="200"
Margin="0,0,61,0" />
<TextBlock Name="Lstate"
Text="{Binding ElementName=MySlider, Path=Value, StringFormat={}{0:P0}}"
VerticalAlignment="Bottom"
HorizontalAlignment="Right"
Width="50" Height="20"
Margin="0,0,0,1" />
Now, in the Code I have the PreviewMouseWheel event with the following Code:
bool handle = (Keyboard.Modifiers & ModifierKeys.Control) > 0;
if (!handle)
return;
double value;
if (e.Delta > 0)
value = 0.1;
else
value = -0.1;
MySlider.Value += value;
And my question is: How to scroll to the actual Mouse Position like AutoCad or some other programs?
Thanks
Sorry for my bad english...
I have a very very good solution now:
VirtualizingStackPanel.IsVirtualizing="True"
VirtualizingStackPanel.VirtualizationMode="Standard"
EnableColumnVirtualization="False"
EnableRowVirtualization="True"
ScrollViewer.CanContentScroll="True"
private void Data_OnPreviewMouseWheel(object sender, MouseWheelEventArgs e)
{
// Scroll to Zoom
if (Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl))
{
// Prevent scroll
e.Handled = true;
var scrollview = FindVisualChild<ScrollViewer>(Data);
if (scrollview != null)
{
// The "+20" are there to account for the scrollbars... i think. Not perfectly accurate.
var relativeMiddle = new Point((Data.ActualWidth + 20) / 2 + (Mouse.GetPosition(Data).X - Data.ActualWidth / 2), (Data.ActualHeight + 20) / 2 + (Mouse.GetPosition(Data).Y - Data.ActualHeight / 2));
var oldLocation = Data.LayoutTransform.Transform(Data.PointFromScreen(relativeMiddle));
// Zoom
MySlider.Value += (e.Delta > 0) ? MySlider.TickFrequency : -MySlider.TickFrequency;
// Scroll
var newLocation = Data.LayoutTransform.Transform(Data.PointFromScreen(relativeMiddle));
// Calculate offset
var shift = newLocation - oldLocation;
if (scrollview.CanContentScroll)
{
// Scroll to the offset (Item)
scrollview.ScrollToVerticalOffset(scrollview.VerticalOffset + shift.Y / scrollview.ViewportHeight);
}
else
{
// Device independent Pixels
scrollview.ScrollToVerticalOffset(scrollview.VerticalOffset + shift.Y);
}
// Device independent Pixels
scrollview.ScrollToHorizontalOffset(scrollview.HorizontalOffset + shift.X);
}
}
}
It zooms to the Mouse Position on the Datagrid with and without virtualization.

Silverlight Button Event Not firing

I know this type of question has been asked before, But I have tried the suggestions to no avail, so hopefully some fresh eyes can help me on this.
I have a Custom Control, which is basically a Border with a grid inside which contains 2 textboxes and a button.
The control also has a octagon that is added in codebehind.
The button's click event does not fire. I gather it has probably got something to do with the controls above it getting the click event instead of the Button, but I don't know how to solve it. Or perhaps because the octagon is drawn afterwards in the code behind.
I have tried so many different things, moving the button, adding another grid, setting the background to Transparent. This is driving me nuts.
Below is the code.
XAML
<UserControl x:Class="HSCGym.UserControls.CustomErrorControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" d:DesignHeight="800" d:DesignWidth="1000">
<Border x:Name="ErrorBorder" BorderBrush="Black" BorderThickness="2" CornerRadius="20" Background="White"
Width="900" Height="700"
VerticalAlignment="Stretch" HorizontalAlignment="Stretch"
Grid.Row="0" Grid.RowSpan="2">
<Border.Effect>
<DropShadowEffect BlurRadius="7" Direction="300" ShadowDepth="6" Color="Black" />
</Border.Effect>
<Grid x:Name="LayoutRoot" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Background="Transparent" >
<Grid.RowDefinitions>
<RowDefinition Height="55" />
<RowDefinition Height="55" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<TextBlock Text="{Binding ErrorText}" HorizontalAlignment="Center" FontSize="40" Grid.Row="0"/>
<TextBlock Text="{Binding ErrorText2}" HorizontalAlignment="Center" FontSize="40" Grid.Row="1"/>
<Button x:Name="btnExit" VerticalAlignment="Bottom" HorizontalAlignment="Left" Margin="38,0,0,20"
Content="Exit" Height="50" Width="200" FontSize="20" Click="btnExit_Click"
Grid.Row="2"/>
</Grid>
</Border>
</UserControl>
And the Code Behind:
public partial class CustomErrorControl
{
public string ErrorText { get; set; }
public string ErrorText2 { get; set; }
public string StopText { get; set; }
private readonly int x;
private readonly int y;
private readonly int r;
public CustomErrorControl(int x, int y, int radius, string stopError)
{
InitializeComponent();
this.x = x;
this.y = y;
r = radius;
StopText = stopError;
DrawOctagon(this.x, this.y, r);
}
public void DrawOctagon(int x, int y, int R)
{
int r2 = (int)(R/Math.Sqrt(2));
// OuterOctagon
Point[] outerOctagon = new Point[8];
outerOctagon[0].X = x;
outerOctagon[0].Y = y - R;
outerOctagon[1].X = x + r2;
outerOctagon[1].Y = y - r2;
outerOctagon[2].X = x + R;
outerOctagon[2].Y = y;
outerOctagon[3].X = x + r2;
outerOctagon[3].Y = y + r2;
outerOctagon[4].X = x;
outerOctagon[4].Y = y + R;
outerOctagon[5].X = x - r2;
outerOctagon[5].Y = y + r2;
outerOctagon[6].X = x - R;
outerOctagon[6].Y = y;
outerOctagon[7].X = x - r2;
outerOctagon[7].Y = y - r2;
HexColor stop1Colour = new HexColor("#FFA30D0D");
HexColor stop2Colour = new HexColor("#FFCA0C0C");
HexColor stop3Colour = new HexColor("#FFF71212");
GradientStop gs1 = new GradientStop { Color = stop1Colour, Offset = 0.98 };
GradientStop gs2 = new GradientStop { Color = stop2Colour, Offset = 0.5 };
GradientStop gs3 = new GradientStop { Color = stop3Colour, Offset = 0.04 };
LinearGradientBrush gb = new LinearGradientBrush
{
StartPoint = new Point(0.77, 0.85),
EndPoint = new Point(0.13, 0.15),
GradientStops = new GradientStopCollection {gs1, gs2, gs3}
};
DropShadowEffect dse = new DropShadowEffect
{
BlurRadius = 8,
Color = Colors.Black,
Direction = 320,
ShadowDepth = 10.0,
Opacity = 0.5
};
Polygon octagonOuter = new Polygon
{
VerticalAlignment = VerticalAlignment.Center,
HorizontalAlignment = HorizontalAlignment.Center,
Fill = gb,
Stroke = new SolidColorBrush(Colors.Black),
StrokeThickness = 5,
StrokeDashArray = new DoubleCollection { 10, 0 },
Effect = dse,
Points = new PointCollection
{
new Point(outerOctagon[0].X, outerOctagon[0].Y),
new Point(outerOctagon[1].X, outerOctagon[1].Y),
new Point(outerOctagon[2].X, outerOctagon[2].Y),
new Point(outerOctagon[3].X, outerOctagon[3].Y),
new Point(outerOctagon[4].X, outerOctagon[4].Y),
new Point(outerOctagon[5].X, outerOctagon[5].Y),
new Point(outerOctagon[6].X, outerOctagon[6].Y),
new Point(outerOctagon[7].X, outerOctagon[7].Y),
}
};
double outerOctCenterY = octagonOuter.Points[6].Y - octagonOuter.Points[2].Y;
double outerOctCenterX = octagonOuter.Points[4].X - octagonOuter.Points[0].X;
var rotate = new RotateTransform { Angle = 22.8, CenterX = outerOctCenterX, CenterY = outerOctCenterY };
octagonOuter.RenderTransform = rotate;
Grid.SetRow(octagonOuter, 2);
TextBlock tbStopError = new TextBlock
{
Text = StopText,
Foreground = new SolidColorBrush(Colors.White),
FontFamily = new FontFamily("Courier New"),
FontSize = 80,
FontWeight = FontWeights.Bold,
VerticalAlignment = VerticalAlignment.Center,
HorizontalAlignment = HorizontalAlignment.Center
};
Grid.SetRow(tbStopError, 2);
LayoutRoot.Children.Add(octagonOuter);
LayoutRoot.Children.Add(tbStopError);
}
private void btnExit_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("Clicked");
}
}
Any ideas?
Many thanks
Neill
Update:
I have tested quickly putting MouseLeftButtonUp events on the grid and the border.
When I click the border, first the grid event fires, then the border event fires, but if I click the button, nothing fires. Does this mean the Button is above the grid and border so should be firing the event?
I will try some of the other suggestions as well in the meant time.
Neill
Update 2:
It gets stranger. I moved the button to the top and then click event fires. What I see is that from a certain Y point and below, absolutely no mouseleftbuttonup or click events fire, nada. This makes no sense. If I go from the bottom and click moving slowly up, then at a certain point, all events start firing.
Neill
Update 3
Hi all,
After removing controls one by one to see what is causing the issue, I now know it is the Border control. If I remove it, all works fine, when it is back, same problem as before. Any ideas?
Thanks
Neill
Update 4
Hi all,
OK so I finally sorted out the problem, so in case anybody finds themselves in a similar situation. It had nothing to do with that page at all. I am loading the page in a frame from a different page and what it seems is that I had to many row definitions set in the grid on the main page. After I corrected that, everything works fine.
Thanks
First try fill button by Transparent color (00000000).
Also you can send solution or part of it to me and I shall try to help.

Area Calculation of CombinedGeometry parts

I need to calculate some areas based on Geometry intersection.
In my example I have the following Geometries:
Left RectangleGeometry
Right RectangleGeometry
EllipseGeometry
The Ellipse is in the middle of the Rectangles and I want two get the following data:
Area of the intersection between the Ellipse and left rectangle
Area of the intersection between the Ellipse and the right rectangle
Total Area of the Ellipse.
The issue is that the total area of the ellipse, EllipseGeometry.GetArea(), and the "LeftEllipseGeometry".GetArea() + "RightEllipseGeometry".GetArea() are different.
The sum of intersections areas have to be the same as the ellipe Area.
I made an example where you can test and see the problem.
MainWindow.xaml.cs
void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
//LEFT
rectLeft = new RectangleGeometry();
rectLeft.Rect = new Rect(new Point(75, 100), new Point(700, 600));
Path pathRectLeft = new Path();
pathRectLeft.Stroke = Brushes.Red;
pathRectLeft.Data = rectLeft;
grdMain.Children.Add(pathRectLeft);
//RIGHT
rectRight = new RectangleGeometry();
rectRight.Rect = new Rect(new Point(700, 100), new Point(1300, 600));
Path pathRectRight = new Path();
pathRectRight.Stroke = Brushes.Green;
pathRectRight.Data = rectRight;
grdMain.Children.Add(pathRectRight);
//ELLIPSE
ellipseGeo = new EllipseGeometry();
ellipseGeo.RadiusX = 200;
ellipseGeo.RadiusY = 200;
ellipseGeo.Center = new Point(700, 350);
Path ellipsePath = new Path();
ellipsePath.Stroke = Brushes.Blue;
ellipsePath.Data = ellipseGeo;
grdMain.Children.Add(ellipsePath);
lblEllipseArea.Content = String.Concat("Area Ellipse = ", ellipseGeo.GetArea());
}
private void Button_Click(object sender, RoutedEventArgs e)
{
CombinedGeometry cgLeft = new CombinedGeometry();
cgLeft.Geometry1 = rectLeft;
cgLeft.Geometry2 = ellipseGeo;
cgLeft.GeometryCombineMode = GeometryCombineMode.Intersect;
Path cgLeftPath = new Path();
cgLeftPath.Stroke = Brushes.Yellow;
cgLeftPath.Data = cgLeft;
grdMain.Children.Add(cgLeftPath);
lblEllipseAreaLeft.Content = String.Concat("Area Left Ellipse = ", cgLeft.GetArea());
CombinedGeometry cgRight = new CombinedGeometry();
cgRight.Geometry1 = rectRight;
cgRight.Geometry2 = ellipseGeo;
cgRight.GeometryCombineMode = GeometryCombineMode.Intersect;
Path cgRightPath = new Path();
cgRightPath.Stroke = Brushes.White;
cgRightPath.Data = cgRight;
grdMain.Children.Add(cgRightPath);
lblEllipseAreaRight.Content = String.Concat("Area Right Ellipse = ", cgRight.GetArea());
lblEllipseTotal.Content = String.Concat("Area Ellipse Total = ", cgLeft.GetArea() + cgRight.GetArea());
}
MainWindow.xaml
<Grid>
<StackPanel Orientation="Vertical" Background="Black">
<Grid Background="Black" Height="700" Name="grdMain">
</Grid>
<Grid Background="Black" Height="150">
<StackPanel Orientation="Vertical">
<Button Height="30" Width="70" Click="Button_Click">Click Me!!!</Button>
<StackPanel Orientation="Horizontal">
<Label Foreground="White" Name="lblEllipseArea"></Label>
<Label Foreground="White" Name="lblEllipseArea2" Margin="20 0 0 0"></Label>
<Label Foreground="White" Name="lblEllipseAreaRight" Margin="20 0 0 0"></Label>
<Label Foreground="White" Name="lblEllipseAreaRight2" Margin="20 0 0 0"></Label>
<Label Foreground="White" Name="lblEllipseAreaLeft" Margin="20 0 0 0"></Label>
<Label Foreground="White" Name="lblEllipseAreaLeft2" Margin="20 0 0 0"></Label>
</StackPanel>
<StackPanel Orientation="Horizontal">
<Label Foreground="White" Name="lblEllipseTotal" Margin="20 0 0 0"></Label>
<Label Foreground="White" Name="lblEllipseTotal2" Margin="20 0 0 0"></Label>
</StackPanel>
</StackPanel>
</Grid>
</StackPanel>
</Grid>
I think you might never get the "exact" areas from the CombinedGeometry. As expected, WPF does not use the "ideal" method to calculate this values. From MSDN: "Some Geometry methods (such as GetArea) produce or use a polygonal approximation of the geometry".
Check MSDN

WPF GridSplitter visiblity

I have a problem regarding GridSplitter visiblity.
In this, whatever I am hosting a Winform DataGridView. The GridSplitter, when dragged is properly visible on other controls. But not on this grid. In fact, whatever I host instead of Datagridview, becomes the topmost control, which makes the GridSplitter hide behind it.
<Grid>
<Grid.RowDefinitions>
<RowDefinition Name="rowForButton"/>
<RowDefinition Name="rowForGridSplitter" Height="Auto" MinHeight="81" />
</Grid.RowDefinitions>
<Button Grid.Row="0" Height="50" Width="110" Content="Button in First Row"/>
<my:WindowsFormsHost Panel.ZIndex="0" Grid.Row="1" Margin="30,11,138,0" x:Name="winHost" Height="58" VerticalAlignment="Top" OpacityMask="Transparent">
<win:DataGridView x:Name="dataGridView"></win:DataGridView>
</my:WindowsFormsHost>
<GridSplitter BorderThickness="1" Panel.ZIndex="1" Grid.Row="1" HorizontalAlignment="Stretch" Height="5" ShowsPreview="True" VerticalAlignment="Top">
</GridSplitter>
</Grid>
Usually you should either put a GridSplitter into its own grid cell or ensure via margins that no control can overlap it. But I don't know whether that exactly applies to you here. See also here.
I encountered this problem also, there is my solution:
var splitter = new GridSplitter()
{
HorizontalAlignment = HorizontalAlignment.Stretch,
VerticalAlignment = VerticalAlignment.Stretch,
FocusVisualStyle = null,
ShowsPreview = true,
Background = new SolidColorBrush(new Color() { R = 1, G = 1, B = 1, A = 1 }),
};
// non-style / essential window which will display over your WinForm control
var PopupWindowForSplitter = new PopupWindow()
{
Background = new SolidColorBrush(new Color() { R = 1, G = 1, B = 1, A = 1 }),
Visibility = Visibility.Collapsed
};
PopupWindowForSplitter.Show();
...
Point _ptForSplitterDrag = new Point(0,0);
splitter.DragStarted += (o, e) =>
{
var pt = splitter.PointToScreen(new Point());
_ptForSplitterDrag = splitter.PointToScreen(Mouse.GetPosition(splitter));
PopupWindowForSplitter.Left = pt.X;
PopupWindowForSplitter.Top = pt.Y;
PopupWindowForSplitter.Height = splitter.ActualHeight;
PopupWindowForSplitter.Width = splitter.ActualWidth;
PopupWindowForSplitter.Activate();
PopupWindowForSplitter.Visibility = Visibility.Visible;
};
splitter.DragDelta += (o, e) =>
{
var pt = splitter.PointToScreen(Mouse.GetPosition(splitter)) - _ptForSplitterDrag
+ splitter.PointToScreen(new Point());
if (splitter.ResizeDirection == GridResizeDirection.Rows)
{
PopupWindowForSplitter.Top = pt.Y;
}
else
{
PopupWindowForSplitter.Left = pt.X;
}
};
splitter.DragCompleted += (o, e) =>
{
var initializeData = typeof(GridSplitter).GetMethod("InitializeData", BindingFlags.NonPublic | BindingFlags.Instance);
var moveSplitter = typeof(GridSplitter).GetMethod("MoveSplitter", BindingFlags.NonPublic | BindingFlags.Instance);
if (moveSplitter != null && initializeData != null)
{
initializeData.Invoke(splitter, new object[] { true });
var pt = splitter.PointToScreen(Mouse.GetPosition(splitter)) - _ptForSplitterDrag;
if (splitter.ResizeDirection == GridResizeDirection.Rows)
{
moveSplitter.Invoke(splitter, new object[] { 0, pt.Y });
}
else
{
moveSplitter.Invoke(splitter, new object[] { pt.X, 0 });
}
}
PopupWindowForSplitter.Visibility = Visibility.Collapsed;
};
Maybe there are some issues in my description because of my poor english, but I think the code is enough to explain it.
Windows Forms controls are always rendered seperately from your WPF controls, and as a result will always appear over your WPF application.
See Hosting a Microsoft Win32 Window in WPF (subheading Notable Differences in Output Behavior) for more info.
Try using a WPF-native DataGrid control. There are a couple of commercial third-party controls you can buy, or you could take a look at one provided by Microsoft (currently still in CTP):
Xceed DataGrid
Telerik RadGridView
Microsoft DataGrid CTP
In your situation, the quickest fix would be to move the GirdSplitter to the Row with the Button:
<Grid>
<Grid.RowDefinitions>
<RowDefinition Name="rowForButton"/>
<RowDefinition Name="rowForGridSplitter" Height="Auto" MinHeight="81" />
</Grid.RowDefinitions>
<Button Grid.Row="0" Height="50" Width="110" Content="Button in First Row"/>
<my:WindowsFormsHost Panel.ZIndex="0" Grid.Row="1" Margin="30,11,138,0" x:Name="winHost" Height="58" VerticalAlignment="Top" OpacityMask="Transparent">
<win:DataGridView x:Name="dataGridView"></win:DataGridView>
</my:WindowsFormsHost>
<GridSplitter BorderThickness="1" Panel.ZIndex="1" Grid.Row="0" HorizontalAlignment="Stretch" Height="5" ShowsPreview="True" VerticalAlignment="Bottom">
</GridSplitter>
</Grid>
Now just adjust the margins to make sure there is some space between the button and the grid splitter.
The solution would be to add a 'Windows Form' label inside the grid splitter, and to do so programmatically after the addition of the DataGridView so it appears on top of it, as follows:
void AddLabelToSplitter()
{
string template =
#" <ControlTemplate
xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'
xmlns:mn='clr-namespace:MyNameSpace;assembly=MyAssembly'
xmlns:wf='clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms'
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml' TargetType='{x:Type GridSplitter}'>
<mn:ExtendedWindowsFormsHost x:Name='Grid_Splitter_WindowsFormsHost' HorizontalAlignment='Stretch' VerticalAlignment='Stretch'>
<wf:Label Dock='Fill' BackColor='DarkGray'></wf:Label>
</mn:ExtendedWindowsFormsHost>
</ControlTemplate>";
Grid_Splitter.Template = (ControlTemplate)XamlReader.Parse(template);
}
Using a regular windows form host would not work, as it wouldn't pass down the mouse events to the splitter, so use the ExtendedWindowsFormsHost instead from below link:
Keep Mouse Events bubbling from WindowsFormsHost on

Resources