Xaml: MouseLeftButtonUp event not working - c#

I have a xaml code for Button declared as ControlTemplate
App.xaml
<!--Style for button start here-->
<Style x:Key="myButtonStyle" TargetType="Border">
<EventSetter Event="Border.MouseLeftButtonDown" Handler="ButtonDown" />
<EventSetter Event="Border.MouseLeftButtonUp" Handler="ButtonUp" />
<EventSetter Event="Border.MouseEnter" Handler="ButtonEnter" />
<EventSetter Event="Border.MouseLeave" Handler="ButtonLeave"/>
</Style>
<!--Style for myButtonStyle ends here-->
<!--Control Template for button start here-->
<ControlTemplate TargetType="Button" x:Key="buttonPrimary">
<Grid Width="{TemplateBinding Width}">
<Border Height="35" Width="{TemplateBinding Width}" Style="{StaticResource myButtonStyle}" Background="{TemplateBinding Background}" CornerRadius="3" Loaded="borderLoaded" x:Name="myButton">
<ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" >
<TextBlock.Foreground>
White
</TextBlock.Foreground>
<TextBlock.FontSize>14</TextBlock.FontSize>
</ContentPresenter>
</Border>
</Grid>
</ControlTemplate>
And In another file I have handled all mouse event ..
Main.cs
private void ButtonDown(object sender, RoutedEventArgs e)
{
Console.WriteLine("ButtonDown");
}//Button Down method ends here
private void ButtonUp(object sender, RoutedEventArgs e)
{
Console.WriteLine("Button Up");
}//ButtonUp method ends here
private void ButtonLeave(object sender, RoutedEventArgs e)
{
Console.WriteLine("ButtonLeave");
}
private void ButtonEnter(object sender, RoutedEventArgs e)
{
Console.WriteLine("ButtonEnter");
}
In main.xaml I am calling these button..
Main.xaml
<Button Content="ButtonPrimary" Width="110" Background="#428bca" Template="{StaticResource buttonPrimary}" />
All the event are firing except MouseLeftButtonUp ..??

The Button's click event eats MouseUp events.
So:
<Style x:Key="buttonPrimary" TargetType="Button">
<EventSetter Event="Click" Handler="ButtonBase_OnClick"/>
<EventSetter Event="PreviewMouseLeftButtonDown" Handler="ButtonDown" />
<EventSetter Event="PreviewMouseLeftButtonUp" Handler="ButtonUp" />
<EventSetter Event="MouseEnter" Handler="ButtonEnter" />
<EventSetter Event="MouseLeave" Handler="ButtonLeave"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Grid Width="{TemplateBinding Width}">
<Border Height="35" Width="{TemplateBinding Width}" Background="{TemplateBinding Background}" CornerRadius="3" x:Name="myButton">
<ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" >
<TextBlock.Foreground>
White
</TextBlock.Foreground>
<TextBlock.FontSize>14</TextBlock.FontSize>
</ContentPresenter>
</Border>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
Then add the ButtonBase_OnClick event that just handles the click event:
private void ButtonBase_OnClick(object sender, RoutedEventArgs e){
e.Handled = true;
}
And Change your Button from Template= to Style= then you will get all your events.

Related

Why does my buttons not change background if I comment out the Window.CommandBindings?

So I've been playing around with creating a custom title bar using WPF and this is what I have
<!--Add the WindowChrome object-->
<WindowChrome.WindowChrome>
<WindowChrome CaptionHeight="34" />
</WindowChrome.WindowChrome>
<Window.Resources>
<ResourceDictionary>
<Style x:Key="CaptionButtonStyle" TargetType="Button">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Grid x:Name="LayoutRoot" Background="Transparent" Width="44" Height="30">
<TextBlock x:Name="txt" Text="{TemplateBinding Content}" FontFamily="Segoe MDL2 Assets" FontSize="10"
Foreground="Black" HorizontalAlignment="Center" VerticalAlignment="Center"
RenderOptions.ClearTypeHint="Auto" TextOptions.TextRenderingMode="Aliased" TextOptions.TextFormattingMode="Display"/>
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName="LayoutRoot" Property="Background" Value="#E5E5E5"/>
<Setter TargetName="txt" Property="Foreground" Value="#000000"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<!--Minimize-->
<Style x:Key="MinimizeButtonStyle" TargetType="Button" BasedOn="{StaticResource CaptionButtonStyle}">
<Setter Property="Content" Value=""/>
</Style>
<!--Maximize-->
<Style x:Key="MaximizeButtonStyle" TargetType="Button" BasedOn="{StaticResource CaptionButtonStyle}">
<Setter Property="Content" Value=""/>
</Style>
<!--Restore-->
<Style x:Key="RestoreButtonStyle" TargetType="Button" BasedOn="{StaticResource CaptionButtonStyle}">
<Setter Property="Content" Value=""/>
</Style>
<!--Close-->
<Style x:Key="CloseButtonStyle" TargetType="Button" BasedOn="{StaticResource CaptionButtonStyle}">
<Setter Property="Content" Value=""/>
</Style>
</ResourceDictionary>
</Window.Resources>
<!-- Title bar button commands -->
<Window.CommandBindings>
<CommandBinding Command="{x:Static SystemCommands.CloseWindowCommand}" CanExecute="CommandBinding_CanExecute" Executed="CommandBinding_Executed_Close" />
<CommandBinding Command="{x:Static SystemCommands.MaximizeWindowCommand}" CanExecute="CommandBinding_CanExecute" Executed="CommandBinding_Executed_Maximize" />
<CommandBinding Command="{x:Static SystemCommands.MinimizeWindowCommand}" CanExecute="CommandBinding_CanExecute" Executed="CommandBinding_Executed_Minimize" />
<CommandBinding Command="{x:Static SystemCommands.RestoreWindowCommand}" CanExecute="CommandBinding_CanExecute" Executed="CommandBinding_Executed_Restore" />
</Window.CommandBindings>
<Border x:Name="MainWindowBorder" BorderBrush="LightCoral" BorderThickness="0" >
<Grid x:Name="parentContainer" Background="LightBlue">
<Grid.RowDefinitions>
<RowDefinition Height ="Auto"/>
<RowDefinition Height ="*"/>
</Grid.RowDefinitions>
<!--Window chrome-->
<Grid Grid.Row="0" Height="30" Background="#F999">
<StackPanel Orientation="Horizontal" HorizontalAlignment="Left" VerticalAlignment="Center">
<!--App icon-->
<Image Source="/Resources/watermelon.ico" Width="18" Margin="2" HorizontalAlignment="Left" VerticalAlignment="Center" />
<TextBlock Text="Sweet App" FontFamily="Arial" Margin="4 3 0 0" />
</StackPanel>
<!--Caption buttons-->
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right" >
<Button Style="{StaticResource MinimizeButtonStyle}" WindowChrome.IsHitTestVisibleInChrome="True" ToolTip="Minimize"
Command="{x:Static SystemCommands.MinimizeWindowCommand}"/>
<Button x:Name="RestoreButton" Visibility="Collapsed" Style="{StaticResource RestoreButtonStyle}"
Command="{x:Static SystemCommands.RestoreWindowCommand}" WindowChrome.IsHitTestVisibleInChrome="True" ToolTip="Restore"/>
<Button x:Name="MaximizeButton" Visibility="Visible" Style="{StaticResource MaximizeButtonStyle}"
Command="{x:Static SystemCommands.MaximizeWindowCommand}" WindowChrome.IsHitTestVisibleInChrome="True" ToolTip="Maximize" />
<Button Style="{StaticResource CloseButtonStyle}" WindowChrome.IsHitTestVisibleInChrome="True" ToolTip="Close"
Command="{x:Static SystemCommands.CloseWindowCommand}"/>
</StackPanel>
</Grid>
<!--App content-->
<Grid Grid.Row="1" x:Name="AppArea">
<Path Data="M50,0L100,50 50,100 0,50z" Fill="White" Stretch="Fill" Stroke="Black" StrokeThickness="2" />
</Grid>
</Grid>
</Border>
And that works great!
However if I were to comment out this part
<Window.CommandBindings>
<CommandBinding Command="{x:Static SystemCommands.CloseWindowCommand}" CanExecute="CommandBinding_CanExecute" Executed="CommandBinding_Executed_Close" />
<CommandBinding Command="{x:Static SystemCommands.MaximizeWindowCommand}" CanExecute="CommandBinding_CanExecute" Executed="CommandBinding_Executed_Maximize" />
<CommandBinding Command="{x:Static SystemCommands.MinimizeWindowCommand}" CanExecute="CommandBinding_CanExecute" Executed="CommandBinding_Executed_Minimize" />
<CommandBinding Command="{x:Static SystemCommands.RestoreWindowCommand}" CanExecute="CommandBinding_CanExecute" Executed="CommandBinding_Executed_Restore" />
</Window.CommandBindings>
Then when I hover over the buttons (Minimize, Maximize and Close) they don't change color anymore and there are no obvious errors presented to me. And as far as I know, it shouldn't change anything UI related since the actual trigger for changing the button background is already defined above in the Window.Resources
Why is this happening?
Here's the code behind
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
StateChanged += MainWindowStateChangeRaised;
}
// Can execute
private void CommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = true;
}
// Minimize
private void CommandBinding_Executed_Minimize(object sender, ExecutedRoutedEventArgs e)
{
SystemCommands.MinimizeWindow(this);
}
// Maximize
private void CommandBinding_Executed_Maximize(object sender, ExecutedRoutedEventArgs e)
{
SystemCommands.MaximizeWindow(this);
}
// Restore
private void CommandBinding_Executed_Restore(object sender, ExecutedRoutedEventArgs e)
{
SystemCommands.RestoreWindow(this);
}
// Close
private void CommandBinding_Executed_Close(object sender, ExecutedRoutedEventArgs e)
{
SystemCommands.CloseWindow(this);
}
// State change
private void MainWindowStateChangeRaised(object sender, EventArgs e)
{
if (WindowState == WindowState.Maximized)
{
MainWindowBorder.BorderThickness = new Thickness(8);
RestoreButton.Visibility = Visibility.Visible;
MaximizeButton.Visibility = Visibility.Collapsed;
}
else
{
MainWindowBorder.BorderThickness = new Thickness(0);
RestoreButton.Visibility = Visibility.Collapsed;
MaximizeButton.Visibility = Visibility.Visible;
}
}
}

Attaching Click Event To Button's Context MenuItem Within ListBoxItem

I'm trying to create a download bar like chrome.
The issue I'm currently having is trying to bind the click event to the button's context menu within the listboxitem. When the context menuitem is clicked, it says the action is not found.
<ControlTemplate TargetType="{x:Type ListBoxItem}">
<Button BorderBrush="Transparent" BorderThickness="0" telerik:StyleManager.Theme="Windows8" Click="ButtonBase_OnClick">
<StackPanel Name="Panel" SnapsToDevicePixels="True"
Orientation="Horizontal" Margin="1 0"
Height="30">
<ContentControl Margin="0 0 10 0" Height="20">
<ContentControl.Style>
<Style TargetType="ContentControl">
<Setter Property="ContentTemplate" Value="{StaticResource Icons.File}"></Setter>
</Style>
</ContentControl.Style>
</ContentControl>
<TextBlock Foreground="Black" Text="{Binding FileName}"
VerticalAlignment="Center"
TextAlignment="Center"
Margin="1 0 0 0"/>
<Button x:Name="ExpandButton" Background="Transparent" Click="ExpandButton_OnClick" BorderThickness="0" VerticalAlignment="Center" ContextMenuService.IsEnabled="false">
<Button.ContextMenu>
<ContextMenu x:Name="popup">
<MenuItem Header="Open" cal:Message.Attach="[Click] = [Open($this)]"></MenuItem>
</ContextMenu>
</Button.ContextMenu>
<ContentControl ContentTemplate="{StaticResource Icons.ArrowUp}" Width="10" Height="10" Margin="2" VerticalAlignment="Center"/>
</Button>
<Rectangle Width="2" Fill="Gray" Margin="0 0 0 0"/>
</StackPanel>
</Button>
</ControlTemplate>
I could bind it behind code(xaml.cs) side of the application but I also lose track of what item is the context suppose to point to. To do that, i replaced caliburn's click event with a regular Click event. The SelectedItem and SelectedItems is null or empty, respectively.
private void MenuItem_OnClick(object sender, RoutedEventArgs e)
{
var originalSource = e.OriginalSource;
var selectedItem = FileListBox.SelectedItem;
var SelectedItems = FileListBox.SelectedItems;
}
Haven't tested but something along these lines should open the context menu on right or left click:
<Button x:Name="ExpandButton" Background="Transparent" Click="ContextMenu_Click" BorderThickness="0" VerticalAlignment="Center" ContextMenuService.IsEnabled="false">
<Button.Style>
<Style TargetType="{x:Type Button}">
<Style.Triggers>
<EventTrigger RoutedEvent="Click">
<EventTrigger.Actions>
<BeginStoryboard>
<Storyboard>
<BooleanAnimationUsingKeyFrames Storyboard.TargetProperty="ContextMenu.IsOpen">
<DiscreteBooleanKeyFrame KeyTime="0:0:0" Value="True"/>
</BooleanAnimationUsingKeyFrames>
</Storyboard>
</BeginStoryboard>
</EventTrigger.Actions>
</EventTrigger>
</Style.Triggers>
<Setter Property="ContextMenu">
<Setter.Value>
<ContextMenu x:Name="popup" MenuItem.Click="menuItem_Click">
<MenuItem Header="Open" cal:Message.Attach="[Click] = [Open($this)]"></MenuItem>
</ContextMenu>
</Setter.Value>
</Setter>
</Style>
</Button.Style>
<ContentControl ContentTemplate="{StaticResource Icons.ArrowUp}" Width="10" Height="10" Margin="2" VerticalAlignment="Center"/>
</Button>
As for the code-behind, the following worked for me in my last tug with a similar issue:
DependencyObject mainDep = new DependencyObject();
private void ContextMenu_Click(object sender, RoutedEventArgs e)
{
DependencyObject dep = (DependencyObject)e.OriginalSource;
while ((dep != null) && !(dep is ListBoxItem))
{
dep = VisualTreeHelper.GetParent(dep);
}
mainDep = dep;
}
private void menuItem_Click(object sender, RoutedEventArgs e)
{
DependencyObject dep = mainDep;
if (dep is ListBoxItem)
{
...
DO your stuff here
...
}
}
Let me know how these work for you

check PasswordBox Value WPF

I have a password box, but i also have a textblock as hint text within the control template. I'd like this to be removed when the password box has a value. I have tried this below but it doesn't work, how can I do this?
Simplified XAML :
<PasswordBox Height="20" Name="pwdBox" PasswordChanged="pwdBox_PasswordChanged" Style="{DynamicResource PasswordBoxStyle1}"/>
<Style x:Key="PasswordBoxStyle1" TargetType="{x:Type PasswordBox}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type PasswordBox}">
<Border x:Name="Border" .. >
<StackPanel ..>
<TextBlock x:Name="LabelTextBlock" ...
Text="Password Label" />
<Grid>
<ScrollViewer x:Name="PART_ContentHost"
Focusable="false"
HorizontalScrollBarVisibility="Hidden"
VerticalScrollBarVisibility="Hidden"/>
<TextBlock x:Name="HintTextBlock"
Focusable="False"
IsHitTestVisible="False"
Opacity="0"
Text="Enter Your Password" />
</Grid>
</StackPanel>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
Code Behind :
private void pwdBox_PasswordChanged(object sender, RoutedEventArgs e)
{
if (pwdBox.SecurePassword.Length == 0)
{
HintTextBlock.IsVisible = true;
}
else
{
HintTextBlock.IsVisible = false;
}
}
It says that the name 'HintTextBlock does not exist in the current context'
Since, the text box HintTextBlock is part of Template of PassworkBox so it can not accessed directly as it is not part of direct control of window. Use the FindName to find the control in template of passwordbox.
TextBlock hintTextBlock = pwdBox.Template.FindName("HintTextBlock", pwdBox) as TextBlock;
if (pwdBox.SecurePassword.Length == 0)
{
hintTextBlock.Visiblility = Visiblitity.Visible;
}
else
{
hintTextBlock.Visiblility = Visiblility.Collapsed;
}

Simulate a long mouseOver wpf

I have a datagrid which contains hyperlinks in a DatagridTemplateColumn like the following :
<DataGridTemplateColumn Width="170" SortMemberPath="Joueur.EtatCivil.Joueur_nom" CanUserReorder="False" CanUserResize="True" Header="">
<DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate />
</DataGridTemplateColumn.CellEditingTemplate>
<DataGridTemplateColumn.CellStyle>
<Style TargetType="DataGridCell" BasedOn="{StaticResource DatagridCellHyperlinkStyle}" >
<Setter Property="Template">
<Setter.Value>
<ControlTemplate>
<Border Padding="{TemplateBinding Padding}" Width="Auto" VerticalAlignment="Center" SnapsToDevicePixels="True">
<TextBlock Foreground="{TemplateBinding Foreground}" Width="Auto" TextTrimming="CharacterEllipsis">
<Hyperlink IsEnabled="{TemplateBinding IsEnabled}">
<InlineUIContainer TextDecorations="{Binding Path=TextDecorations, RelativeSource={RelativeSource AncestorType=TextBlock}}" Foreground="{Binding Path=Foreground, RelativeSource={RelativeSource AncestorType=TextBlock}}">
<ContentPresenter Content="{Binding DataContext.Joueur.EtatCivil.NomComplet, RelativeSource={RelativeSource AncestorType=DataGridRow}}"/>
</InlineUIContainer>
<Hyperlink.Style>
<Style TargetType="Hyperlink" BasedOn="{StaticResource HyperlinkStyle}">
<EventSetter Event="Hyperlink.Click" Handler="ClickEvent" />
<EventSetter Event="Hyperlink.MouseEnter" Handler="MouseOverEvent" />
<EventSetter Event="Hyperlink.MouseLeave" Handler="ClicJoueurMouseLeaveEvent" />
</Style>
</Hyperlink.Style>
</Hyperlink>
</TextBlock>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</DataGridTemplateColumn.CellStyle>
</DataGridTemplateColumn>
This works fine and as expected but I have trouble when I just move my cursor hover many lines in a small time (<0.5s maybe).
My MouseEnterEvent calls a method named "Show();" and my MouseLeaveEvent a method named "Hide();"
This show/hide a small popup to display to the user more data. The problem is that my show(); method update a Wpf toolkit chart which seems to have trouble to be updated with this frequency (10 times in 0.5s). The binding seems to "crash" and never works again.
this helped me : Binding update adds news series to WPF Toolkit chart (instead of replacing/updating series) )
I update my chart like this :
this.colonnes.ItemsSource = null;
_DataGraph = new ObservableCollection<GraphiqueValeurs>();
_DataGraph.Add(new GraphiqueValeurs(value, "my string");
this.colonnes.ItemsSource = _DataGraph;
this.colonnes.UpdateLayout();
With the following xaml :
<chartingToolkit:Chart VerticalAlignment="Top" HorizontalAlignment="Center" FontFamily="/BPM2015;component/#Open Sans Condensed" BorderBrush="Transparent" Name="columnChart" Title="Column Series Demo" Foreground="{DynamicResource CouleurTexte}" >
<chartingToolkit:ColumnSeries Name="colonnes" Foreground="{DynamicResource CouleurTexte}" DependentValueBinding="{Binding Valeur}"
IndependentValueBinding="{Binding Name}"
DataPointStyle="{StaticResource ColorByPreferenceColumn}"
>
<chartingToolkit:ColumnSeries.DependentRangeAxis>
<chartingToolkit:LinearAxis Orientation="Y" Minimum="0" Maximum="20" Title="" Foreground="Transparent" ShowGridLines="True">
<chartingToolkit:LinearAxis.MajorTickMarkStyle>
<Style TargetType="Line">
<Setter Property="Visibility" Value="Collapsed" />
</Style>
</chartingToolkit:LinearAxis.MajorTickMarkStyle>
</chartingToolkit:LinearAxis>
</chartingToolkit:ColumnSeries.DependentRangeAxis>
</chartingToolkit:ColumnSeries>
<chartingToolkit:Chart.LegendStyle>
<Style TargetType="Control">
<Setter Property="Width" Value="0" />
<Setter Property="Height" Value="0" />
</Style>
</chartingToolkit:Chart.LegendStyle>
<chartingToolkit:Chart.TitleStyle>
<Style TargetType="Control">
<Setter Property="Width" Value="0" />
<Setter Property="Height" Value="0" />
</Style>
</chartingToolkit:Chart.TitleStyle>
So my question is : How I can avoid all these quick mouseEnter ? I'd like to avoid my mouseEnter function to call the "Show()" method if the cursor doesn't stay at least 0.4s on the hyperlink.
How could I do that ?
This
Thank you
You can use a DispatcherTimer to add a delay to calling your function and combine that with a bool flag that is set to true in the MouseEnter handler and set to false in the MouseLeave handler. Try this:
private DispatcherTimer timer = new DispatcherTimer();
private isMouseOver = false;
...
timer.Interval = TimeSpan.FromMilliseconds(400);
timer.Tick += Timer_Tick;
...
private void MouseEnterHandler(object sender, MouseEventArgs e)
{
isMouseOver = true;
timer.Start();
}
private void MouseLeaveHandler(object sender, MouseEventArgs e)
{
isMouseOver = false;
timer.Stop();
}
private void Timer_Tick(object sender, EventArgs e)
{
if (isMouseOver) Show();
timer.Stop();
}

Make a Thumb control sizable using the mouse to drag an edge

I need a thumb control that can be sized using a mouse. When the user hovers the mouse over one of the ends a size cursor should be displayed and when the user clicks and drags the end of the control it will be re-sized.
How can that be achieved?
Here is one I made a while ago, it allows Move and Resize, but you can remove the Move logic and it should work fine (the style is still a bit messy, but it works pretty well)
Its based on ContentControl so you can add any Element inside and Move/Resize on a Canvas, It uses 3 Adorners, one for Resize, one for Move and one to display information (current size)
Here is a full working example if you want to test/use/modify/improve :)
Code:
namespace WpfApplication21
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
}
public class ResizeThumb : Thumb
{
public ResizeThumb()
{
DragDelta += new DragDeltaEventHandler(this.ResizeThumb_DragDelta);
}
private void ResizeThumb_DragDelta(object sender, DragDeltaEventArgs e)
{
Control designerItem = this.DataContext as Control;
if (designerItem != null)
{
double deltaVertical, deltaHorizontal;
switch (VerticalAlignment)
{
case VerticalAlignment.Bottom:
deltaVertical = Math.Min(-e.VerticalChange, designerItem.ActualHeight - designerItem.MinHeight);
designerItem.Height -= deltaVertical;
break;
case VerticalAlignment.Top:
deltaVertical = Math.Min(e.VerticalChange, designerItem.ActualHeight - designerItem.MinHeight);
Canvas.SetTop(designerItem, Canvas.GetTop(designerItem) + deltaVertical);
designerItem.Height -= deltaVertical;
break;
default:
break;
}
switch (HorizontalAlignment)
{
case HorizontalAlignment.Left:
deltaHorizontal = Math.Min(e.HorizontalChange, designerItem.ActualWidth - designerItem.MinWidth);
Canvas.SetLeft(designerItem, Canvas.GetLeft(designerItem) + deltaHorizontal);
designerItem.Width -= deltaHorizontal;
break;
case HorizontalAlignment.Right:
deltaHorizontal = Math.Min(-e.HorizontalChange, designerItem.ActualWidth - designerItem.MinWidth);
designerItem.Width -= deltaHorizontal;
break;
default:
break;
}
}
e.Handled = true;
}
}
public class MoveThumb : Thumb
{
public MoveThumb()
{
DragDelta += new DragDeltaEventHandler(this.MoveThumb_DragDelta);
}
private void MoveThumb_DragDelta(object sender, DragDeltaEventArgs e)
{
Control designerItem = this.DataContext as Control;
if (designerItem != null)
{
double left = Canvas.GetLeft(designerItem);
double top = Canvas.GetTop(designerItem);
Canvas.SetLeft(designerItem, left + e.HorizontalChange);
Canvas.SetTop(designerItem, top + e.VerticalChange);
}
}
}
public class SizeAdorner : Adorner
{
private Control chrome;
private VisualCollection visuals;
private ContentControl designerItem;
protected override int VisualChildrenCount
{
get
{
return this.visuals.Count;
}
}
public SizeAdorner(ContentControl designerItem)
: base(designerItem)
{
this.SnapsToDevicePixels = true;
this.designerItem = designerItem;
this.chrome = new Control();
this.chrome.DataContext = designerItem;
this.visuals = new VisualCollection(this);
this.visuals.Add(this.chrome);
}
protected override Visual GetVisualChild(int index)
{
return this.visuals[index];
}
protected override Size ArrangeOverride(Size arrangeBounds)
{
this.chrome.Arrange(new Rect(new Point(0.0, 0.0), arrangeBounds));
return arrangeBounds;
}
}
}
Xaml:
<Window x:Class="WpfApplication21.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication21"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<Style TargetType="{x:Type ContentControl}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ContentControl}">
<Grid DataContext="{Binding RelativeSource={RelativeSource TemplatedParent}}">
<local:MoveThumb Cursor="SizeAll">
<local:MoveThumb.Style>
<Style TargetType="{x:Type local:MoveThumb}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:MoveThumb}">
<Rectangle Fill="Transparent" />
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</local:MoveThumb.Style>
</local:MoveThumb>
<Control x:Name="resizer">
<Control.Style>
<Style TargetType="{x:Type Control}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Control}">
<Grid>
<Grid Opacity="0" Margin="-3">
<local:ResizeThumb Height="3" Cursor="SizeNS" VerticalAlignment="Top" HorizontalAlignment="Stretch"/>
<local:ResizeThumb Width="3" Cursor="SizeWE" VerticalAlignment="Stretch" HorizontalAlignment="Left"/>
<local:ResizeThumb Width="3" Cursor="SizeWE" VerticalAlignment="Stretch" HorizontalAlignment="Right"/>
<local:ResizeThumb Height="3" Cursor="SizeNS" VerticalAlignment="Bottom" HorizontalAlignment="Stretch"/>
<local:ResizeThumb Width="7" Height="7" Margin="-2" Cursor="SizeNWSE" VerticalAlignment="Top" HorizontalAlignment="Left"/>
<local:ResizeThumb Width="7" Height="7" Margin="-2" Cursor="SizeNESW" VerticalAlignment="Top" HorizontalAlignment="Right"/>
<local:ResizeThumb Width="7" Height="7" Margin="-2" Cursor="SizeNESW" VerticalAlignment="Bottom" HorizontalAlignment="Left"/>
<local:ResizeThumb Width="7" Height="7" Margin="-2" Cursor="SizeNWSE" VerticalAlignment="Bottom" HorizontalAlignment="Right"/>
</Grid>
<Grid IsHitTestVisible="False" Opacity="1" Margin="-3">
<Grid.Resources>
<Style TargetType="{x:Type Ellipse}">
<Setter Property="SnapsToDevicePixels" Value="true" />
<Setter Property="Stroke" Value="#FFC8C8C8" />
<Setter Property="StrokeThickness" Value=".5" />
<Setter Property="Width" Value="7" />
<Setter Property="Height" Value="7" />
<Setter Property="Margin" Value="-2" />
<Setter Property="Fill" Value="Silver" />
</Style>
</Grid.Resources>
<Rectangle SnapsToDevicePixels="True" StrokeThickness="1" Margin="1" Stroke="Black" StrokeDashArray="4 4"/>
<Ellipse HorizontalAlignment="Left" VerticalAlignment="Top"/>
<Ellipse HorizontalAlignment="Right" VerticalAlignment="Top"/>
<Ellipse HorizontalAlignment="Left" VerticalAlignment="Bottom"/>
<Ellipse HorizontalAlignment="Right" VerticalAlignment="Bottom"/>
</Grid>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Control.Style>
</Control>
<Grid x:Name="sizeInfo" SnapsToDevicePixels="True">
<Path Stroke="Red" StrokeThickness="1" Height="10" VerticalAlignment="Bottom" Margin="-2,0,-2,-15" Stretch="Fill" Data="M0,0 0,10 M 0,5 100,5 M 100,0 100,10"/>
<TextBlock Text="{Binding Width}" Background="White" Padding="3,0,3,0" Foreground="Red" Margin="0,0,0,-18" HorizontalAlignment="Center" VerticalAlignment="Bottom"/>
<Path Stroke="Red" StrokeThickness="1" Width="10" HorizontalAlignment="Right" Margin="0,-2,-15,-2" Stretch="Fill" Data="M5,0 5,100 M 0,0 10,0 M 0,100 10,100"/>
<TextBlock Text="{Binding Height}" Background="White" Foreground="Red" Padding="3,0,3,0" Margin="0,0,-18,0" HorizontalAlignment="Right" VerticalAlignment="Center">
<TextBlock.LayoutTransform>
<RotateTransform Angle="90" CenterX="1" CenterY="0.5"/>
</TextBlock.LayoutTransform>
</TextBlock>
</Grid>
<ContentPresenter Content="{TemplateBinding Content}"/>
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName="sizeInfo" Property="Visibility" Value="Visible" />
</Trigger>
<Trigger Property="IsMouseOver" Value="False">
<Setter TargetName="sizeInfo" Property="Visibility" Value="Hidden" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
<Canvas>
<ContentControl Width="183" Height="110" Canvas.Left="166" Canvas.Top="50" />
</Canvas>
</Window>
Result:
With content inside (Button)
Sorry the cursors do not show when using SnipTool

Categories

Resources