How to fix ToggleButton hover detection? - c#

When I hover over the button, it will turn aqua, however it does not switch back to black once removing the cursor.
I am new to C# and I'm trying to get a grasp of the basic application functions. They seem very different from Java's Swing and JavaFX.
private void Mouse_Move(object sender, MouseEventArgs e)
{
var element = (UIElement) e.Source;
var c = Grid.GetColumn(element);
var r = Grid.GetRow(element);
if (c == 0 && r == 0)
{
MenuButton.Fill = Brushes.Aqua;
}
else
{
MenuButton.Fill = Brushes.Black;
}
}
<Grid ShowGridLines="False" Background="#282828">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="100"></ColumnDefinition>
<ColumnDefinition></ColumnDefinition>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="100"></RowDefinition>
<RowDefinition Height="100"></RowDefinition>
<RowDefinition Height="100"></RowDefinition>
<RowDefinition Height="100"></RowDefinition>
<RowDefinition Height="100"></RowDefinition>
<RowDefinition Height="100"></RowDefinition>
<RowDefinition Height="100"></RowDefinition>
<RowDefinition Height="68"></RowDefinition>
</Grid.RowDefinitions>
<Rectangle Grid.Column="0" Grid.RowSpan="1000">
<Rectangle.Fill>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="#1c1c1c" Offset="0"/>
<GradientStop Color="#1c1c1c" Offset="1"/>
</LinearGradientBrush>
</Rectangle.Fill>
</Rectangle>
<Rectangle x:Name="MenuButton" MouseMove="Mouse_Move" Grid.Column="0" Grid.Row="0">
<Rectangle.Fill>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="#1c1c1c" Offset="0"/>
<GradientStop Color="#1c1c1c" Offset="1"/>
</LinearGradientBrush>
</Rectangle.Fill>
</Rectangle>
<ToggleButton Click="Button_Click" Grid.Row="0" Grid.Column="0" Height="32" Width="32" Checked = "HandleCheck" Unchecked = "HandleUnchecked">
<ToggleButton.Template>
<ControlTemplate>
<Image Width="32" Height="32" Source="Resources/menu.png"></Image>
</ControlTemplate>
</ToggleButton.Template>
</ToggleButton>
</Grid>

Use MouseLeave and MouseEnter instead of MouseMove
XAML
<Rectangle x:Name="MenuButton" MouseEnter="Mouse_Enter" Grid.Column="0" Grid.Row="0" MouseLeave="Mouse_Leave">
C#
private void Mouse_Enter(object sender, MouseEventArgs e)
{
var element = (UIElement) e.Source;
var c = Grid.GetColumn(element);
var r = Grid.GetRow(element);
if (c == 0 && r == 0)
{
MenuButton.Fill = Brushes.Aqua;
//Change fill to Aqua when the cursor enters
}
}
private void Mouse_Leave(object sender, MouseEventArgs e)
{
var element = (UIElement) e.Source;
var c = Grid.GetColumn(element);
var r = Grid.GetRow(element);
if (c == 0 && r == 0)
{
MenuButton.Fill = Brushes.Black;
//Change fill to Black when the cursor leaves
}
}

Related

UWP: Adjusting InkCanvas size when writing/drawing

I'm learning how to develop UWP apps and I'm using Microsoft's documentation as tutorials/research.
I want to have an InkCanvas design similar to OneNote where the InkCanvas height and width can expand (as you're writing/drawing and reach the end of the window size) and can shrink (when you erase ink strokes and the extra size can decrease based on the position of the ink strokes until you get back to the original size).
I'm able to increase the InkCanvas width and height, but can't decrease when erasing ink strokes.
Here is a MainPage.xaml code:
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<TextBlock Text="Heading"
FontSize="36"
FontWeight="Bold"
Margin="10"
Grid.Column="0"
Grid.Row="0"/>
<Grid BorderBrush="Red"
BorderThickness="2"
Margin="10"
Grid.Column="0"
Grid.Row="1">
<ScrollViewer HorizontalScrollBarVisibility="Auto"
HorizontalScrollMode="Enabled"
VerticalScrollBarVisibility="Auto"
VerticalScrollMode="Enabled" >
<Grid BorderBrush="Blue"
BorderThickness="2"
Margin="1">
<InkCanvas Name="inkCanvas"/>
</Grid>
</ScrollViewer>
</Grid>
And the MainPage.cs code:
public MainPage()
{
this.InitializeComponent();
nkCanvas.InkPresenter.StrokeInput.StrokeEnded += adjustInkCanvasSize;
}
private async void adjustInkCanvasSize(InkStrokeInput sender, PointerEventArgs args)
{
await Task.Delay(100);
var XBound = inkCanvas.InkPresenter.StrokeContainer.BoundingRect.Bottom;
if (XBound > inkCanvas.ActualHeight - 200)
inkCanvas.Height = XBound + 200;
var YBound = inkCanvas.InkPresenter.StrokeContainer.BoundingRect.Right;
if (YBound > inkCanvas.ActualWidth - 200)
inkCanvas.Width = YBound + 200;
}
The c# code also came from another stackoverflow solution, but not able to figure out the "decrease" part.
Any help would be much appreciated. Thanks
If you want the InkCanvas control to shrink when you erase ink strokes and the extra size can decrease based on the position of the ink strokes until the original size, you need to add the InkPresenter.StrokesErased event to manage the size of the InkCanvas control. For example:
Here is a MainPage.xaml code( To facilitate testing, I added the mouse support):
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<TextBlock Text="Heading"
FontSize="36"
FontWeight="Bold"
Margin="10"
Grid.Column="0"
Grid.Row="0"/>
<Grid BorderBrush="Red"
BorderThickness="2"
Margin="10"
Grid.Column="0"
Grid.Row="1">
<Grid.RowDefinitions>
<RowDefinition Height="auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<InkToolbar x:Name="inkToolbar" VerticalAlignment="Top" Margin="10,0,10,0"
TargetInkCanvas="{x:Bind inkCanvas}" Grid.Row="0"/>
<ScrollViewer HorizontalScrollBarVisibility="Auto"
HorizontalScrollMode="Enabled" Grid.Row="1"
VerticalScrollBarVisibility="Auto"
VerticalScrollMode="Enabled" >
<Grid BorderBrush="Blue"
BorderThickness="2"
Margin="1">
<InkCanvas Name="inkCanvas" />
</Grid>
</ScrollViewer>
</Grid>
</Grid>
And the MainPage.cs code:
public sealed partial class MainPage : Page
{
private double originalX; //The original size
private double originalY;
private double maxX=0.0;
private double maxY=0.0;
private bool flag = true;
public MainPage()
{
this.InitializeComponent();
inkCanvas.InkPresenter.InputDeviceTypes = CoreInputDeviceTypes.Mouse | CoreInputDeviceTypes.Touch |
CoreInputDeviceTypes.Pen;
inkCanvas.InkPresenter.StrokeInput.StrokeEnded += adjustInkCanvasSize;
inkCanvas.InkPresenter.StrokesErased += InkPresenter_StrokesErased;
}
private async void InkPresenter_StrokesErased(InkPresenter sender, InkStrokesErasedEventArgs args)
{
await Task.Delay(100);
//The coordinate of the lower right corner of the erased ink stoke
var erasedInkX= args.Strokes.ElementAt(0).BoundingRect.Bottom;
var erasedInkY = args.Strokes.ElementAt(0).BoundingRect.Right;
var XBound = inkCanvas.InkPresenter.StrokeContainer.BoundingRect.Bottom;
if (erasedInkX >=maxX&&XBound < inkCanvas.ActualHeight + 100)
{
if (XBound - 100 > originalX)
inkCanvas.Height = XBound - 100;
else
inkCanvas.Height = originalX; //The size of InkCanvas shrinks to the original size.
maxX = inkCanvas.Height;
}
var YBound = inkCanvas.InkPresenter.StrokeContainer.BoundingRect.Right;
if (erasedInkY>=maxY&&YBound < inkCanvas.ActualWidth + 100)
{
if (YBound - 100 > originalY)
{
inkCanvas.Width = YBound - 100;
}
else
inkCanvas.Width = originalY;
maxY = inkCanvas.Width;
}
}
private async void adjustInkCanvasSize(InkStrokeInput sender, PointerEventArgs args)
{
await Task.Delay(100);
if(flag)
{
flag = false;
originalX = inkCanvas.ActualHeight; //Get the original size
originalY = inkCanvas.ActualWidth;
}
var XBound = inkCanvas.InkPresenter.StrokeContainer.BoundingRect.Bottom;
if (XBound > maxX)
maxX = XBound; //maxX and maxY always hold the maximum size of StrokeContainer
if (XBound > inkCanvas.ActualHeight - 200)
inkCanvas.Height = XBound + 200;
var YBound = inkCanvas.InkPresenter.StrokeContainer.BoundingRect.Right;
if (YBound > maxY)
maxY = YBound;
if (YBound > inkCanvas.ActualWidth - 200)
inkCanvas.Width = YBound + 200;
}
}

EllipseGeometry Shrink & Fade Without Exceeding Canvas Bounds in C# WPF

How to make animation stay within the canvas at bigger sizes when the user clicks around the edge of the canvas? Currently, if sizes are too big and if user clicks near the edge of the canvas, the ellipse will grow outside of the canvas to cover the buttons. I need the animation to stay within the canvas to make it look like a slice of pizza essentially.
Should look like this:
Size 50 where user clicks near top left of canvas
Currently looks like this:
Size 50 where user clicks near top left of canvas
Xaml:
<Window.Resources>
<Storyboard x:Key="anim">
<DoubleAnimation
Storyboard.TargetName="myCircle"
Storyboard.TargetProperty="RadiusX"
AutoReverse="True"/>
<DoubleAnimation
Storyboard.TargetName="myCircle"
Storyboard.TargetProperty="RadiusY"
AutoReverse="True"/>
<DoubleAnimation
Storyboard.TargetName="path"
Storyboard.TargetProperty="Opacity"
AutoReverse="True"/>
</Storyboard>
</Window.Resources>
<Grid HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
<Grid.RowDefinitions>
<RowDefinition Height="23"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<DockPanel HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Grid.Row="0" Margin="0,0,0,1">
<Menu DockPanel.Dock="Top" Height="23">
<MenuItem Header="Main" RenderTransformOrigin="-1.896,0.643" HorizontalAlignment="Left" Width="39" Height="23">
<MenuItem Header="Exit, Esc" Click="MenuItem_Click_Exit"/>
</MenuItem>
</Menu>
</DockPanel>
<Grid HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Grid.Row="1" Name="pane">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="150"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Grid HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Grid.Column="0" Name="pane2">
<Grid.RowDefinitions>
<RowDefinition Height="35"/>
<RowDefinition Height="35"/>
<RowDefinition Height="35"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="50"/>
</Grid.ColumnDefinitions>
<Label Content="Size" Grid.Row="0" Grid.Column="0" Height="25" VerticalAlignment="Stretch"/>
<Label Content="Fill Color" Grid.Row="1" Grid.Column="0" Height="25" VerticalAlignment="Stretch"/>
<Label Content="Stroke Thickness" Grid.Row="2" Grid.Column="0" Height="25" VerticalAlignment="Stretch"/>
<Label Content="Stroke Color" Grid.Row="3" Grid.Column="0" VerticalAlignment="Top" Height="25"/>
<Slider x:Name="Slider_Size" Grid.Row="0" Grid.Column="1" Height="20" Width="45"
Minimum="5" Maximum="50"
AutoToolTipPlacement="BottomRight"
TickFrequency="1"
IsSnapToTickEnabled="True"
PreviewMouseUp="Slider_Size_PreviewMouseUp"/>
<Label Name="tempSize" Content="{Binding Path=Value, ElementName=Slider_Size}" Margin="0,25,0,131" Grid.Row="3" Visibility="Hidden"/>
<ComboBox Name="ComboBox_FillColor" Grid.Row="1" Grid.Column="1" Height="20" Width="45" SelectionChanged="ComboBox_FillColor_Selected"/>
<TextBox Name="textBox" Grid.Row="2" Grid.Column="1" Height="20" Width="45" TextChanged="textBox_TextChanged"/>
<ComboBox Name="ComboBox_StrokeColor" Grid.Row="3" Grid.Column="1" VerticalAlignment="Top" Height="20" Width="45" SelectionChanged="ComboBox_StrokeColor_Selected"/>
</Grid>
<Border Name ="border" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" BorderBrush="Black" Grid.Column="1" BorderThickness="2">
<Canvas Name="canvas" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" MouseDown="Canvas_MouseDown">
<Path x:Name="path">
<Path.Data>
<EllipseGeometry x:Name="myCircle"/>
</Path.Data>
</Path>
<Canvas.Background>
<SolidColorBrush Color="White" Opacity="0"/>
</Canvas.Background>
</Canvas>
</Border>
</Grid>
</Grid>
C#:
public partial class MainWindow : Window
{
private int size;
private SolidColorBrush fillColor;
private SolidColorBrush strokeColor;
private List<SolidColorBrush> colors;
private int fillIndex;
private int strokeIndex;
private int strokeThickness = 1;
private int fillColorDefault;
private int strokeColorDefault;
private Point? _start = null;
public MainWindow()
{
InitializeComponent();
addColors();
textBox.Text = strokeThickness.ToString();
parse();
}
private void MenuItem_Click_Exit(object sender, RoutedEventArgs e) { Environment.Exit(1); }
private void Window_KeyUp_ESC(object sender, KeyEventArgs e)
{
if (Key.Escape == e.Key)
MenuItem_Click_Exit(sender, e);
}
private void addColors()
{
colors = typeof(Brushes).GetProperties().Select(p => p.GetValue(null, null) as SolidColorBrush).ToList();
int count = 0;
foreach (SolidColorBrush color in colors)
{
ComboBox_FillColor.Items.Add(new Rectangle() { Height = 12, Width = 17.5, Fill = color });
ComboBox_StrokeColor.Items.Add(new Rectangle() { Height = 12, Width = 17.5, Fill = color });
if (color.Color == Colors.Red)
{
fillIndex = count;
fillColor = colors[fillIndex];
ComboBox_FillColor.SelectedIndex = count;
fillColorDefault = count;
}
if (color.Color == Colors.Black)
{
strokeIndex = count;
strokeColor = colors[strokeIndex];
ComboBox_StrokeColor.SelectedIndex = count;
strokeColorDefault = count;
}
count++;
}
}
private void ComboBox_FillColor_Selected(object sender, RoutedEventArgs e) { fillIndex = ComboBox_FillColor.SelectedIndex; fillColor = colors[fillIndex]; }
private void ComboBox_StrokeColor_Selected(object sender, RoutedEventArgs e) { strokeIndex = ComboBox_StrokeColor.SelectedIndex; strokeColor = colors[strokeIndex]; }
private void Canvas_MouseDown(object sender, MouseButtonEventArgs e)
{
path.Stroke = strokeColor;
path.StrokeThickness = strokeThickness;
path.Fill = fillColor;
path.HorizontalAlignment = HorizontalAlignment.Stretch;
path.VerticalAlignment = VerticalAlignment.Stretch;
path.Stretch = Stretch.None;
path.SetValue(Grid.ColumnProperty, 1);
_start = Mouse.GetPosition((UIElement)sender);
myCircle.Center = (Point)_start;
var sb = FindResource("anim") as Storyboard;
var x = sb.Children.First() as DoubleAnimation;
x.To = 2 * size;
x.Duration = new Duration(TimeSpan.FromSeconds(0.5));
var y = sb.Children.ElementAt(1) as DoubleAnimation;
y.To = 2 * size;
y.Duration = new Duration(TimeSpan.FromSeconds(0.5));
var z = sb.Children.Last() as DoubleAnimation;
z.From = 0.0;
z.To = 1.0;
z.Duration = new Duration(TimeSpan.FromSeconds(0.5));
sb.Begin(path);
}
private void textBox_TextChanged(object sender, TextChangedEventArgs e)
{
//regex where any string of chars besides numbers
Regex pattern = new Regex(#"^([^0-9]*)$", RegexOptions.Compiled);
Match result = pattern.Match(textBox.Text);
if (textBox.Text.ToString() == string.Empty)
return;
else if (result.Success)
{
MessageBox.Show("Invalid character entered. Integer numbers only. Stroke Thickness will be reseted to a default of 1.");
strokeThickness = 1;
textBox.Text = strokeThickness.ToString();
textBox.SelectAll();
}
else
{
int x;
if (int.TryParse(textBox.Text, out x))
strokeThickness = int.Parse(textBox.Text);
}
}
private void Slider_Size_PreviewMouseUp(object sender, MouseButtonEventArgs e)
{
parse();
}
private void parse()
{
int x;
if (int.TryParse(tempSize.Content.ToString(), out x))
size = x;
}
}
}
So you don't need the ellipse to stay within the Canvas, but you want to clip away the parts leaving it, right? Just set ClipToBounds (of Canvas) to true (can be done in Xaml).

Canvas RuleLines With grid UWP

I'm working in a program which contains a canvas ,
This canvas includes some shapes and RuleLines ,
I added a grid to the canvas and it looked like this
the problem is the program is not smooth when I Manipulate or Zoom this canvas,
this is the Grid code in C# :
public void GridPartitions (Grid grid)
{
for (int ii = 0; ii < 50; ii++)
{
MyGrid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(20) });
MyGrid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(20) });
}
for (int row = 0; row < 50; row++)
{
for(int coulmn = 0; coulmn < 50; coulmn++)
{
var PartitionRectangle = new Rectangle();
PartitionRectangle.Stroke = new SolidColorBrush() { Color = Color.FromArgb(255, 0, 0, 0) };
PartitionRectangle.StrokeThickness = 0.2;
grid.Children.Add(PartitionRectangle);
Grid.SetRow(PartitionRectangle, row);
Grid.SetColumn(PartitionRectangle, coulmn);
}
}
}
However in Microsoft OneNote UWP
it has this option and it runs very smooth whatever the the number of the RuleLines and looks like this :
Any ideas to Improve My Code ?
Thank You.
here is My new Code .. Its better But still not smooth
I tried to Make everything in OOP as much as possible
XAML:
<Canvas Name="MyCanvas01" Background="Transparent"
MinWidth="2500" MinHeight="720"
Width="2500" Height="720"
HorizontalAlignment="Left" VerticalAlignment="Top"
RenderTransformOrigin="0.5,0.5"
ManipulationDelta="MyCanvas01_ManipulationDelta" ManipulationMode="All"
SizeChanged="MyCanvas01_SizeChanged">
<ItemsControl ItemsSource="{x:Bind HorizontalLines}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Line X1="{Binding From.X}" Y1="{Binding From.Y}"
X2="{Binding ElementName=MyCanvas01, Path=Width}" Y2="{Binding To.Y}"
Stroke="black" StrokeThickness="0.5"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
<ItemsControl ItemsSource="{x:Bind VerticalLines}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Line X1="{Binding From.X}" Y1="{Binding From.Y}"
X2="{Binding To.X }" Y2="{Binding ElementName=MyCanvas01, Path=Height}"
Stroke="black" StrokeThickness="0.5"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
<Canvas.RenderTransform>
<TransformGroup>
<ScaleTransform x:Name="st01"/>
<TranslateTransform x:Name="TT01" />
</TransformGroup>
</Canvas.RenderTransform>
</Canvas>
C#:
public void DrawMissingLines(ObservableCollection<LineBindingPointsClass> lines, double missingLines, Point from, Point to ,int gg)
{
if (missingLines > 0)
{
for (int ii = 0; ii < missingLines; ii++)
{
lines.Add(new LineBindingPointsClass() { From = from , To = to });
if (gg == 1)
{
from.X += 25;
to.X += 25;
}
else if (gg == 2)
{
from.Y += 25;
to.Y += 25;
}
}
}
else if (missingLines < 0)
{
for (int ii = 0; ii < -missingLines; ii++)
{
lines.Remove(lines.Last());
}
}
}
private void MyCanvas01_SizeChanged(object sender, SizeChangedEventArgs e)
{
Canvas SizedCanvas = (Canvas)sender;
double missingVerticalLines, MissingHorizontalLines;
missingVerticalLines = (Math.Floor(SizedCanvas.Width) - VerticalLines.Count() * 25 ) / 25;
MissingHorizontalLines = (Math.Floor(SizedCanvas.Height) - HorizontalLines.Count() * 25) / 25;
DrawMissingLines(VerticalLines, missingVerticalLines,
new Point(VerticalLines.Count()*25 , 0),
new Point(VerticalLines.Count() * 25 , SizedCanvas.Height ),1);
DrawMissingLines(HorizontalLines, MissingHorizontalLines
, new Point(0,HorizontalLines.Count() * 25 ),
new Point( SizedCanvas.Width, HorizontalLines.Count() * 25) ,2);
}
For smooth zooming and Support gestures and (Ctrl + MouseWheel) you can put the canvas inside ScrollViewer.
Here is example Code:
<ScrollViewer ZoomMode="Enabled" ZoomSnapPointsType="Mandatory">
<Canvas Background="White" RenderTransformOrigin="0.5,0.5"
ManipulationDelta="MyCanvas_ManipulationDelta" ManipulationMode="All" CacheMode="BitmapCache">
<Rectangle Width="500" Height="500" Fill="Black"/>
</Canvas>
</ScrollViewer>
actually its very smooth
Now I'm working on adding adaptive Grid
here is the final code
working perfect
smooth and adaptive ,the background grids are updating according to the Canvas size change
I added two borders
the background is LinearGradientBrush for each border ,,........
enough talking and here is the Code:
<ScrollViewer Name="BorderScrollViewer" ZoomMode="Enabled" ZoomSnapPointsType="Mandatory"
HorizontalScrollMode="Disabled"
VerticalScrollMode="Disabled"
VerticalScrollBarVisibility="Disabled" HorizontalScrollBarVisibility="Disabled"
ManipulationDelta="MyCanvas01_ManipulationDelta" ManipulationMode="All">
<Canvas Name="MyCanvas01" Background="White"
MinWidth="1200" MinHeight="720"
Width="1200" Height="720"
HorizontalAlignment="Left" VerticalAlignment="Top"
RenderTransformOrigin="0.5,0.5"
ManipulationDelta="MyCanvas01_ManipulationDelta" ManipulationMode="All"
SizeChanged="MyCanvas01_SizeChanged"
>
<Border VerticalAlignment="Stretch"
Width="{Binding ElementName=MyCanvas01,Path=Width}"
Height="{Binding ElementName=MyCanvas01,Path=Height}">
<Border.Background>
<LinearGradientBrush EndPoint="25,0" SpreadMethod="Repeat" MappingMode="Absolute" StartPoint="-25,0">
<LinearGradientBrush.RelativeTransform>
<CompositeTransform CenterY="0.5" CenterX="0.5" />
</LinearGradientBrush.RelativeTransform>
<GradientStop Color="Transparent" Offset="0.53"/>
<GradientStop Color="Transparent" Offset="0.48"/>
<GradientStop Color="#FF320064" Offset="0.49"/>
<GradientStop Color="#FF320061" Offset="0.51"/>
<GradientStop Color="#FF320068" Offset="0.51"/>
</LinearGradientBrush>
</Border.Background>
</Border>
<Border VerticalAlignment="Stretch" HorizontalAlignment="Stretch"
Width="{Binding ElementName=MyCanvas01,Path=Width}"
Height="{Binding ElementName=MyCanvas01,Path=Height}" >
<Border.Background>
<LinearGradientBrush EndPoint="0,25" SpreadMethod="Repeat" MappingMode="Absolute" StartPoint="0,-25">
<LinearGradientBrush.RelativeTransform>
<CompositeTransform CenterY="0.5" CenterX="0.5"/>
</LinearGradientBrush.RelativeTransform>
<GradientStop Color="Transparent" Offset="0.53"/>
<GradientStop Color="Transparent" Offset="0.48"/>
<GradientStop Color="#FF320064" Offset="0.49"/>
<GradientStop Color="#FF320061" Offset="0.51"/>
<GradientStop Color="#FF320068" Offset="0.51"/>
</LinearGradientBrush>
</Border.Background>
</Border>
<Canvas.RenderTransform>
<TransformGroup>
<TranslateTransform x:Name="TT01" />
</TransformGroup>
</Canvas.RenderTransform>
</Canvas>
</ScrollViewer>

Set selection to view box

Hello I have some buttons randomly assigned in my WPF application like so:
partial class Window1
{
private void button3_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("action 3");
}
void button2Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("action 2");
}
void button1Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("action 1");
}
public Window1()
{
this.InitializeComponent();
populateButtons();
}
public void populateButtons()
{
double xPos;
double yPos;
Random ranNum = new Random();
foreach (var routedEventHandler in new RoutedEventHandler[] { button1Click, button2Click, button3_Click })
{
Button foo = new Button();
Style buttonStyle = Window.Resources["CurvedButton"] as Style;
int sizeValue = 100;
foo.Width = sizeValue;
foo.Height = sizeValue;
xPos = ranNum.Next(200);
yPos = ranNum.Next(250);
foo.HorizontalAlignment = HorizontalAlignment.Left;
foo.VerticalAlignment = VerticalAlignment.Top;
foo.Margin = new Thickness(xPos, yPos, 0, 0);
foo.Style = buttonStyle;
foo.Click += routedEventHandler;
LayoutRoot.Children.Add(foo);
}
}
}
}
I set the area in which to populate the buttons like so:
int xPos;
int yPos;
xPos = ranNum.Next(239);
yPos = ranNum.Next(307);
foo.HorizontalAlignment = HorizontalAlignment.Left;
foo.VerticalAlignment = VerticalAlignment.Top;
foo.Margin = new Thickness(xPos, yPos, 0, 0);
What I would prefer to do now is set this area with a view box named viewbox1 (original eh!) ;)
Is there a way to do this in the code behind?
XAML:
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xml:lang="en-US"
x:Class="DynamicButtons.Window1"
x:Name="Window"
Title="Dynamic Buttons"
WindowState="Normal" WindowStyle="None" AllowsTransparency="True" Background="Transparent"
Width="840" Height="600" Icon="shape_group.png">
<Window.Resources>
<Style x:Key="CurvedButton" BasedOn="{x:Null}" TargetType="{x:Type Button}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<ControlTemplate.Resources>
<Storyboard x:Key="OnMouseMove1">
<ColorAnimationUsingKeyFrames BeginTime="00:00:00" Storyboard.TargetName="rectangle" Storyboard.TargetProperty="(Shape.Fill).(SolidColorBrush.Color)">
<SplineColorKeyFrame KeyTime="00:00:00" Value="#FFFFFFFF"/>
<SplineColorKeyFrame KeyTime="00:00:00.3000000" Value="#7CE1DBDB"/>
</ColorAnimationUsingKeyFrames>
<DoubleAnimationUsingKeyFrames BeginTime="00:00:00" Storyboard.TargetName="rectangle" Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[0].(ScaleTransform.ScaleX)">
<SplineDoubleKeyFrame KeyTime="00:00:00" Value="1"/>
<SplineDoubleKeyFrame KeyTime="00:00:00.3000000" Value="1.66"/>
</DoubleAnimationUsingKeyFrames>
<DoubleAnimationUsingKeyFrames BeginTime="00:00:00" Storyboard.TargetName="rectangle" Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[0].(ScaleTransform.ScaleY)">
<SplineDoubleKeyFrame KeyTime="00:00:00" Value="1"/>
<SplineDoubleKeyFrame KeyTime="00:00:00.3000000" Value="1.66"/>
</DoubleAnimationUsingKeyFrames>
</Storyboard>
<Storyboard x:Key="OnMouseLeave1">
<DoubleAnimationUsingKeyFrames BeginTime="00:00:00" Storyboard.TargetName="rectangle" Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[0].(ScaleTransform.ScaleX)">
<SplineDoubleKeyFrame KeyTime="00:00:00.8000000" Value="1.78"/>
<SplineDoubleKeyFrame KeyTime="00:00:01" Value="1"/>
</DoubleAnimationUsingKeyFrames>
<DoubleAnimationUsingKeyFrames BeginTime="00:00:00" Storyboard.TargetName="rectangle" Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[0].(ScaleTransform.ScaleY)">
<SplineDoubleKeyFrame KeyTime="00:00:00.8000000" Value="1.78"/>
<SplineDoubleKeyFrame KeyTime="00:00:01" Value="1"/>
</DoubleAnimationUsingKeyFrames>
</Storyboard>
<Storyboard x:Key="OnClick1">
<ColorAnimationUsingKeyFrames BeginTime="00:00:00" Storyboard.TargetName="rectangle" Storyboard.TargetProperty="(Shape.Fill).(SolidColorBrush.Color)">
<SplineColorKeyFrame KeyTime="00:00:00.2000000" Value="#FFFFFFFF"/>
<SplineColorKeyFrame KeyTime="00:00:00.3000000" Value="#BFA0D1E2"/>
</ColorAnimationUsingKeyFrames>
</Storyboard>
</ControlTemplate.Resources>
<Grid>
<Rectangle RenderTransformOrigin="1,1" Fill="#3FFFFFFF" Stroke="{x:Null}" RadiusX="11" RadiusY="11" x:Name="rectangle">
<Rectangle.RenderTransform>
<TransformGroup>
<ScaleTransform ScaleX="1" ScaleY="1"/>
<SkewTransform AngleX="0" AngleY="0"/>
<RotateTransform Angle="0"/>
<TranslateTransform X="0" Y="0"/>
</TransformGroup>
</Rectangle.RenderTransform>
</Rectangle>
<ContentPresenter SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" RecognizesAccessKey="True"/>
</Grid>
<ControlTemplate.Triggers>
<EventTrigger RoutedEvent="ButtonBase.Click">
<BeginStoryboard x:Name="OnClick1_BeginStoryboard" Storyboard="{StaticResource OnClick1}"/>
</EventTrigger>
<EventTrigger RoutedEvent="Mouse.MouseLeave">
<BeginStoryboard x:Name="OnMouseLeave1_BeginStoryboard" Storyboard="{StaticResource OnMouseLeave1}"/>
</EventTrigger>
<EventTrigger RoutedEvent="FrameworkElement.Loaded"/>
<EventTrigger RoutedEvent="Mouse.MouseEnter">
<BeginStoryboard x:Name="OnMouseMove1_BeginStoryboard" Storyboard="{StaticResource OnMouseMove1}"/>
</EventTrigger>
<Trigger Property="IsFocused" Value="True"/>
<Trigger Property="IsDefaulted" Value="True"/>
<Trigger Property="IsMouseOver" Value="True"/>
<Trigger Property="IsPressed" Value="True"/>
<Trigger Property="IsEnabled" Value="False"/>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
<Setter Property="Background">
<Setter.Value>
<LinearGradientBrush EndPoint="0,1" StartPoint="0,0">
<GradientStop Color="#FFF3F3F3" Offset="0"/>
<GradientStop Color="#FFEBEBEB" Offset="0.5"/>
<GradientStop Color="#FFDDDDDD" Offset="0.5"/>
<GradientStop Color="#E1CDCDCD" Offset="1"/>
</LinearGradientBrush>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
<Window.Triggers>
<EventTrigger RoutedEvent="FrameworkElement.Loaded"/>
</Window.Triggers>
<Grid x:Name="LayoutRoot">
<Grid Name="MainLayoutGrid" Background="#2b2b2b">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="4" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="4" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="4" />
<RowDefinition Height="25" />
<RowDefinition Height="*" />
<RowDefinition Height="4" />
</Grid.RowDefinitions>
<Grid Grid.Column="1" Grid.Row="1" Name="TitleGrid">
<Grid.RowDefinitions>
<RowDefinition Height="2"/>
<RowDefinition Height="*"/>
<RowDefinition Height="4"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="100"/>
</Grid.ColumnDefinitions>
<Grid Grid.Row="1" Grid.Column="0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="20"/>
<ColumnDefinition Width="4"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<Image Grid.Column="0" Name="ImageIcon" Stretch="Uniform"/>
<TextBlock Grid.Column="2" Name="Titleblk" Foreground="White">Wanna be Title</TextBlock>
</Grid>
<Grid Grid.Row="0" Grid.Column="2" Grid.RowSpan="2">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="25"/>
<ColumnDefinition Width="25"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Button Name="btnMin" Grid.Column="1" Grid.ColumnSpan="2" Margin="8,4,42,-4">
<Button.RenderTransform>
<ScaleTransform ScaleX="0.8" ScaleY="0.8"></ScaleTransform>
</Button.RenderTransform>
<Button.Clip>
<RectangleGeometry RadiusX="1000" RadiusY="1000" Rect="0,0,18,20" />
</Button.Clip>
</Button>
<Button Name="btnMax" Grid.Column="2" Margin="2,4,23,-4">
<Button.RenderTransform>
<ScaleTransform ScaleX="0.8" ScaleY="0.8"></ScaleTransform>
</Button.RenderTransform>
<Button.Clip>
<RectangleGeometry RadiusX="1000" RadiusY="1000" Rect="0,0,18,20" />
</Button.Clip>
</Button>
<Button Name="btnClose" Grid.Column="2" Margin="24,0,6,0" BorderBrush="#00000000" BorderThickness="0" ClickMode="Press" Foreground="#00000000" HorizontalAlignment="Stretch" HorizontalContentAlignment="Center" OpacityMask="#82F8F8F8" VerticalAlignment="Stretch" VerticalContentAlignment="Center">
<Button.Clip>
<RectangleGeometry RadiusX="1000" RadiusY="1000" Rect="0,0,20,20" />
</Button.Clip>
</Button>
</Grid>
</Grid>
<Grid Grid.Column="1" Grid.Row="2">
<Grid.Background>
<LinearGradientBrush EndPoint="0.484,0.543" StartPoint="0.478,0.009">
<GradientStop Color="Gray" Offset="1"/>
<GradientStop Color="DarkGray" Offset="0"/>
</LinearGradientBrush>
</Grid.Background>
<UniformGrid>
<Viewbox Height="364" Name="viewbox1" Width="363" VerticalAlignment="Stretch" Margin="6,0,441,164" />
</UniformGrid>
</Grid>
</Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<!--<Canvas Height="284" HorizontalAlignment="Left" Margin="457,66,0,0" Name="canvas1" VerticalAlignment="Top" Width="300" />-->
</Grid>
</Window>
Full Code:
namespace DynamicButtons
{
partial class Window1
{
void button3_Click(object sender, RoutedEventArgs e)
{
if (e.RoutedEvent == FrameworkElement.LoadedEvent)
{
ToolTip t = new ToolTip();
t.Content = "Something helpful";
((Button)sender).ToolTip = t;
((Button)sender).Content = "Hello";
return;
}
MessageBox.Show("Hello you punk");
}
void button2Click(object sender, RoutedEventArgs e)
{
//ToolTip t = new ToolTip();
//t.Content = "Something helpful";
//((Button)sender).ToolTip = t;
//MessageBox.Show("action 2");
}
void button1Click(object sender, RoutedEventArgs e)
{
//ToolTip t = new ToolTip();
//t.Content = "Something helpful";
//((Button)sender).ToolTip = t;
////Button b = new Button();
//((Button)sender).Content = "Hello";
////b.ToolTip = t;
//MessageBox.Show("action 1");
}
public Window1()
{
this.InitializeComponent();
populateButtons();
}
public void populateButtons()
{
double xPos;
double yPos;
UniformGrid grid = new UniformGrid();
Viewbox viewBox = new Viewbox();
viewBox.Name = "viewbox1";
viewBox.Stretch = Stretch.Fill;
viewBox.Child = grid;
LayoutRoot.Children.Add(viewBox);
Random ranNum = new Random();
foreach (var routedEventHandler in new RoutedEventHandler[] { button1Click, button2Click, button3_Click })
{
Button foo = new Button();
Style buttonStyle = Window.Resources["CurvedButton"] as Style;
int sizeValue = 100;
foo.Width = sizeValue;
foo.Height = sizeValue;
xPos = ranNum.Next(100);
yPos = ranNum.Next(150);
foo.HorizontalAlignment = HorizontalAlignment.Left;
foo.VerticalAlignment = VerticalAlignment.Top;
foo.Margin = new Thickness(xPos, yPos, 0, 0);
foo.Style = buttonStyle;
foo.Click += routedEventHandler;
foo.Loaded += routedEventHandler;
grid.Children.Add(foo);
}
}
To add the buttons to a ViewBox you can just do this:
public void populateButtons()
{
double xPos;
double yPos;
UniformGrid grid = new UniformGrid();
viewbox1.Child = grid;
Random ranNum = new Random();
foreach (var routedEventHandler in new RoutedEventHandler[] { button1Click, button2Click, button3_Click })
{
Button foo = new Button();
Style buttonStyle = Window.Resources["CurvedButton"] as Style;
int sizeValue = 100;
foo.Width = sizeValue;
foo.Height = sizeValue;
xPos = ranNum.Next(200);
yPos = ranNum.Next(250);
foo.HorizontalAlignment = HorizontalAlignment.Left;
foo.VerticalAlignment = VerticalAlignment.Top;
foo.Margin = new Thickness(xPos, yPos, 0, 0);
foo.Style = buttonStyle;
foo.Click += routedEventHandler;
grid.Children.Add(foo);
}
}
What is your reasoning for using a Viewbox? Is it for stretch and scale reasons?
I recommend using a Canvas and then you can set your Canvas.Left and Canvas.Top values similarly to how you set xPos and yPos.
Then if you wish to have the stretch / scale features of the Viewbox, you could put the Canvas you created as the child of the Viewbox.
UPDATE: to get the ActualHeight and ActualWidth values of the canvas during runtime you can add an event handler for SizeChanged (easy to do within the XAML but not too hard within code) to handle the change in height/width value during runtime. Here's the code solution:
bool initialized = false; // Should be located in class definition for your window
// ex. within "public partial class WindowName : Window
canvas.SizeChanged += new SizeChangedEventHandler(canvas_SizeChanged);
// Can be located in constructor for window
// ie. public MainWindow() { /* put it right here */ }
then the definition for the event handler can be as follows: (this only creates one button but would work with your for loop.)
Location update This definition below can be located within the class def for your window, but below the definition for the boolean variable "initialized". (ex. w/in "public partial class WindowName : Window")
private void canvas_SizeChanged(object sender, SizeChangedEventArgs e)
{
if (initialized == false) // so this only happens once.
{
int sizeValue = 100;
Random ranNum = new Random();
int modHeight = System.Convert.ToInt32(canvas.ActualHeight)-sizeValue;
int modWidth = System.Convert.ToInt32(canvas.ActualWidth)-sizeValue;
Button foo = new Button();
canvas.Children.Add(foo);
foo.Width = sizeValue;
foo.Height = sizeValue;
xPos = ranNum.Next(239) % modWidth;
yPos = ranNum.Next(307) % modHeight
Canvas.SetLeft(foo, xPos);
Canvas.SetTop(foo, yPos);
initialized = true;
}
}
Or, if you know what size your canvas is going to be you can just manually set modHeight and modWidth to the pixel value of your choice and not have to deal with the event handler.

WPF: hide grid rows with GridSplitter

How can I hide the last two rows after resizing of splitter?
When last two rows are hidden, the webBrowser should fill all the area.
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="5" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<WebBrowser Name="webBrowser" />
<GridSplitter Grid.Row="1" ResizeDirection="Rows"
ResizeBehavior="PreviousAndNext" Width="Auto" Height="5"
HorizontalAlignment="Stretch"
Visibility="...">
</GridSplitter>
<c:MyControl Grid.Row="2" Visibility="..." />
</Grid>
Quick fix of this issue:
public class HideableGridSplitter : GridSplitter
{
private GridLength height;
public HideableGridSplitter()
{
this.IsVisibleChanged += HideableGridSplitter_IsVisibleChanged;
}
void HideableGridSplitter_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
{
Grid parent = base.Parent as Grid;
if (parent == null)
return;
int rowIndex = Grid.GetRow(this);
if (rowIndex + 1 >= parent.RowDefinitions.Count)
return;
var lastRow = parent.RowDefinitions[rowIndex + 1];
if (this.Visibility == Visibility.Visible)
lastRow.Height = height;
else
{
height = lastRow.Height;
lastRow.Height = new GridLength(0);
}
}
}
Make a trigger on MyControl.ActualHeight. If 0, set visibility to collapsed
<DataTrigger Binding="{Binding ElementName=MyControl, Path=ActualHeight}" Value=0>
<Setter Property="Visibility" Value="Collapsed" />
</DataTrigger>

Categories

Resources