Add button to Window Border - c#

I have a WPF window with property WindowStyle="SingleBorderWindow".
Now I want to know how to set a button on left upper corner of the window border.

You probably need to use window chrome library which is described here.

I assume this is so you can re-create the Minimize/Maximize/Close buttons.
You have two options, use a Grid or a DockPanel. I have included a sample for a Grid below.
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
<Grid.RowDefinitions>
<StackPanel Orientation="Horizontal" Margin="2,0" HorizontalAlignment="Right" VerticalAlignment="Top">
</StackPanel>
</Grid>
A Grid with a RowDefinition Height="Auto" that has a StackPanel Orientation="Horizontal" that is right-aligned.
However
If you want to make a true border-less window, you will have more work to do than simply setting the WindowStyle to None.
One main stumbling block I encountered was that when WindowStyle is None, it will not respect the task bar (i.e. overlap it) and you will need to hook into the message pump to set the correct window constraints.
Let me know in the comments if you want to know how to do this, will happy post sample code.

You need to make custom window by setting transparency, background and style like below :
<Window x:Class="WpfApplication2.Window2"
Name="Window2xx"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
Title="window1"
xmlns:m="clr-namespace:WpfApplication2"
AllowsTransparency="True" WindowStyle="None"
WindowStartupLocation="CenterOwner" d:DesignWidth="410" StateChanged="Window_StateChanged"
SizeToContent="WidthAndHeight" ShowInTaskbar="False" Background="Transparent">
<Window.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Style.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Window.Resources>
<Grid>
<m:MasterWindow Width="400">
<m:MasterWindow.WindowTitle>
<ContentPresenter Content="window1" MouseLeftButtonDown="Window_MouseLeftButtonDown"></ContentPresenter>
</m:MasterWindow.WindowTitle>
<m:MasterWindow.Content>
<Grid>
</Grid>
</m:MasterWindow.Content>
</m:MasterWindow>
</Grid>
</Window>
Code behind window2 :
namespace WpfApplication2
{
public partial class Window2 : Window
{
public Window2()
{
InitializeComponent();
}
private void Window_StateChanged(object sender, EventArgs e)
{
if (((Window)sender).WindowState == WindowState.Maximized)
((Window)sender).WindowState = WindowState.Normal;
}
private void Window_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
try
{
DragMove();
}
catch ()
{}
}
}
}
Master window is like below :
namespace WpfApplication2
{
public class MasterWindow : ContentControl
{
public static RoutedCommand CloseWindowCommand;
static MasterWindow()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(MasterWindow), new FrameworkPropertyMetadata(typeof(MasterWindow)));
CloseWindowCommand = new RoutedCommand("CloseWindow", typeof(MasterWindow));
CommandManager.RegisterClassCommandBinding(typeof(MasterWindow), new CommandBinding(CloseWindowCommand, CloseWindowEvent));
}
public static readonly DependencyProperty WindowTitleProperty = DependencyProperty.Register("WindowTitle", typeof(object), typeof(MasterWindow), new UIPropertyMetadata());
public object WindowTitle
{
get { return (object)GetValue(WindowTitleProperty); }
set { SetValue(WindowTitleProperty, value); }
}
private static void CloseWindowEvent(object sender, ExecutedRoutedEventArgs e)
{
MasterWindow control = sender as MasterWindow;
if (control != null)
{
Window objWindow = Window.GetWindow(((FrameworkElement)sender));
if (objWindow != null)
{
if (objWindow.Name.ToLower() != "unlockscreenwindow")
{
Window.GetWindow(((FrameworkElement)sender)).Close();
}
}
}
}
}
}
Styles for master window :
<ResourceDictionary
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"
xmlns:local="clr-namespace:WpfApplication2"
x:Class="MasterWindow">
<Style x:Key="WindowTitle" TargetType="ContentPresenter">
<Setter Property="Control.FontFamily" Value="Segoe UI"></Setter>
<Setter Property="Control.FontSize" Value="14"></Setter>
<Setter Property="Control.FontWeight" Value="SemiBold"></Setter>
<Setter Property="Control.Foreground" Value="White"></Setter>
<Setter Property="Control.VerticalAlignment" Value="Top"></Setter>
<Setter Property="Control.HorizontalAlignment" Value="Left"></Setter>
<Setter Property="Control.VerticalContentAlignment" Value="Top"></Setter>
</Style>
<Style x:Key="closebutton" BasedOn="{x:Null}" TargetType="{x:Type Button}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Grid>
<Rectangle
Opacity="1"
RadiusX="2"
RadiusY="2"
Stroke="#ffffff"
StrokeThickness="1">
<Rectangle.Fill>
<LinearGradientBrush
StartPoint="0.6190476190476191,-0.5"
EndPoint="1.1128888811383928,1.426776123046875">
<LinearGradientBrush.GradientStops>
<GradientStopCollection>
<GradientStop
Color="#2E4C87"
Offset="0" />
<GradientStop
Color="#FFffffff"
Offset="1" />
</GradientStopCollection>
</LinearGradientBrush.GradientStops>
</LinearGradientBrush>
</Rectangle.Fill>
</Rectangle>
<Path
Margin="5,5,5,5"
Stretch="Fill"
Opacity="1"
Data="M 808.8311767578125,278.7662353515625 C808.8311767578125,278.7662353515625 820,268 820,268 "
Stroke="#ffffff"
StrokeThickness="2" />
<Path
Margin="5,5,5,5"
Stretch="Fill"
Opacity="1"
Data="M 809.4155883789062,268.3636474609375 C809.4155883789062,268.3636474609375 820,279 820,279 "
Stroke="#ffffff"
StrokeThickness="2" />
<ContentPresenter SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" RecognizesAccessKey="True"/>
</Grid>
<ControlTemplate.Triggers>
<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>
</Style>
<Style TargetType="{x:Type local:MasterWindow}">
<Setter Property="IsTabStop" Value="False" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:MasterWindow}">
<StackPanel>
<Border x:Name="border" Background="WhiteSmoke" BorderBrush="#2E4C87" BorderThickness="7" CornerRadius="8,8,8,8" >
<Border.BitmapEffect>
<DropShadowBitmapEffect Color="Black" Direction="320" Opacity="0.75" ShadowDepth="8"></DropShadowBitmapEffect>
</Border.BitmapEffect>
<Border.RenderTransform>
<TransformGroup>
<ScaleTransform ScaleX="0.95" ScaleY="0.95"/>
<SkewTransform AngleX="0" AngleY="0"/>
<RotateTransform Angle="0"/>
<TranslateTransform X="0" Y="0"/>
</TransformGroup>
</Border.RenderTransform>
<Border.Triggers>
<EventTrigger RoutedEvent="Border.Loaded">
<BeginStoryboard>
<Storyboard>
<DoubleAnimation Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[0].(ScaleTransform.ScaleX)" From="0" To="0.96" Duration="0:0:0.6"/>
<DoubleAnimation Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[0].(ScaleTransform.ScaleY)" From="0" To="0.96" Duration="0:0:0.6"/>
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</Border.Triggers>
<Grid HorizontalAlignment="Stretch" >
<Grid.RowDefinitions>
<RowDefinition Height="32"></RowDefinition>
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Border BorderThickness="5,5,3,0" Background="#2E4C87" BorderBrush="#2E4C87" CornerRadius="5,4,0,0" VerticalAlignment="Top" Height="32" Margin="-6,-6,-4,0" >
<Grid Background="Transparent" HorizontalAlignment="Stretch" Height="32" VerticalAlignment="Center" >
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="30"/>
</Grid.ColumnDefinitions>
<ContentPresenter Content="{TemplateBinding WindowTitle}" Margin="0,4,0,0" HorizontalAlignment="Stretch" Style="{StaticResource WindowTitle}" />
<Button Name="btnClose" Style="{StaticResource closebutton}" Cursor="Hand" Command="{x:Static local:MasterWindow.CloseWindowCommand}" VerticalAlignment="Top" Height="18" HorizontalAlignment="Right" Width="18" Margin="0,5,8,0" Grid.Column="1" />
</Grid>
</Border>
<Border BorderBrush="Transparent" BorderThickness="7,0,7,7" VerticalAlignment="Top" HorizontalAlignment="Left" CornerRadius="0,0,10,10" Grid.Row="1"></Border>
<ContentPresenter Grid.Row="1" Content="{TemplateBinding Content}" VerticalAlignment="Top" Margin="0,-6,0,0"/>
</Grid>
</Border>
</StackPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>

Related

How to display current date and time on Wpf statusbar

I want to know how to display current date and time on a WPF statusbar.
I know this is too basic a question, but I am new to .net WPF,
and I know this can be done in a Form application easily.
Thanks in advance.
Ting
Create a wpf project. In your MainWindow.xaml add the StatusBar and handle Loaded event of window.
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="WpfApp1.MainWindow"
Title="MainWindow" Height="450" Width="800" Loaded="Window_Loaded">
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<StatusBar Grid.Row="1">
<TextBlock x:FieldModifier="private" x:Name="myDateTime"/>
</StatusBar>
</Grid>
</Window>
In the MainWindow.xaml.cs add the following namespaces (if they are not exist):
using System;
using System.Windows;
using System.Windows.Threading;
And in the Loaded enevt handler you can use DispatcherTimer for update textblock text property every second:
private void Window_Loaded(object sender, RoutedEventArgs e)
{
DispatcherTimer timer = new DispatcherTimer(TimeSpan.FromSeconds(1), DispatcherPriority.Normal, (object s, EventArgs ev) =>
{
this.myDateTime.Text = DateTime.Now.ToString("yyyy/MM/dd hh:mm:ss");
}, this.Dispatcher);
timer.Start();
}
Also there are a lot of examples for customize wpf controls using Template and Style properties. just search for it.
Styles and templates in WPF
The WPF StatusBar control
and many more.
Also you can implement your custom WPFTimer. This simple implementation get you an idea for do this.
public class WPFTimer : TextBlock
{
#region static
public static readonly DependencyProperty IntervalProperty = DependencyProperty.Register("Interval", typeof(TimeSpan), typeof(WPFTimer), new PropertyMetadata(TimeSpan.FromSeconds(1), IntervalChangedCallback));
public static readonly DependencyProperty IsRunningProperty = DependencyProperty.Register("IsRunning", typeof(bool), typeof(WPFTimer), new PropertyMetadata(false, IsRunningChangedCallback));
private static void IntervalChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
WPFTimer wpfTimer = (WPFTimer)d;
wpfTimer.timer.Interval = (TimeSpan)e.NewValue;
}
private static void IsRunningChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
WPFTimer wpfTimer = (WPFTimer)d;
wpfTimer.timer.IsEnabled = (bool)e.NewValue;
}
#endregion
private readonly DispatcherTimer timer;
[Category("Common")]
public TimeSpan Interval
{
get
{
return (TimeSpan)this.GetValue(IntervalProperty);
}
set
{
this.SetValue(IntervalProperty, value);
}
}
[Category("Common")]
public bool IsRunning
{
get
{
return (bool)this.GetValue(IsRunningProperty);
}
set
{
this.SetValue(IsRunningProperty, value);
}
}
public WPFTimer()
{
this.timer = new DispatcherTimer(this.Interval, DispatcherPriority.Normal,this.Timer_Tick ,this.Dispatcher);
this.timer.IsEnabled = false;
}
private void Timer_Tick(object sender, EventArgs e)
{
this.SetValue(TextProperty, DateTime.Now.ToString("yyyy/MM/dd hh:mm:ss"));
}
}
And now you have a control that can use it in the designer.
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApp1"
x:Class="WpfApp1.MainWindow"
Title="MainWindow" Height="450" Width="800">
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<StatusBar Grid.Row="1">
<local:WPFTimer IsRunning="True"/>
</StatusBar>
</Grid>
</Window>
You can do it this way, using wpf animation and binding, and no background code :)
<Window x:Class="WpfApp6.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:system="clr-namespace:System;assembly=System.Runtime"
mc:Ignorable="d"
Title="MainWindow"
Height="450"
Width="800">
<Grid>
<Grid.Resources>
<!--Set x: share to get the latest every time-->
<system:DateTime x:Key="DateTime"
x:Shared="False" />
<Storyboard x:Key="Storyboard">
<!--Use keyframe animation to update datetime -->
<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="DataContext"
Duration="0:0:1"
RepeatBehavior="Forever"
AutoReverse="False">
<DiscreteObjectKeyFrame KeyTime="50%"
Value="{StaticResource DateTime}" />
</ObjectAnimationUsingKeyFrames>
</Storyboard>
</Grid.Resources>
<!--Get datetime from DataContext-->
<TextBlock Text="{Binding RelativeSource={RelativeSource Self},Path=DataContext.Now}"
DataContext="{StaticResource DateTime}">
<TextBlock.Triggers>
<EventTrigger RoutedEvent="Loaded">
<BeginStoryboard Storyboard="{StaticResource Storyboard}" />
</EventTrigger>
</TextBlock.Triggers>
</TextBlock>
</Grid>
</Window>
or like this,a real clock
<Window x:Class="WpfApp6.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:system="clr-namespace:System;assembly=System.Runtime"
mc:Ignorable="d"
Title="MainWindow"
Height="450"
Width="800">
<Window.Resources>
<FrameworkElement x:Key="time" Tag="{x:Static system:DateTime.Now}" />
<TransformGroup x:Key="transformHour">
<TranslateTransform X="{Binding Source={StaticResource time},Path=Tag.Hour}"
Y="{Binding Source={StaticResource time},Path=Tag.Minute}" />
<MatrixTransform Matrix="30 0 0.5 0 0 0" />
</TransformGroup>
<TransformGroup x:Key="transformMinute">
<TranslateTransform X="{Binding Source={StaticResource time},Path=Tag.Minute}"
Y="{Binding Source={StaticResource time},Path=Tag.Second}" />
<MatrixTransform Matrix="6 0 0.1 0 0 0" />
</TransformGroup>
<TransformGroup x:Key="transformSecond">
<TranslateTransform X="{Binding Source={StaticResource time},Path=Tag.Second}" />
<MatrixTransform Matrix="6 0 0 0 0 0" />
</TransformGroup>
<Style TargetType="{x:Type Path}">
<Setter Property="Stroke"
Value="{DynamicResource {x:Static SystemColors.WindowTextBrushKey}}" />
<Setter Property="StrokeThickness" Value="3" />
<Setter Property="StrokeDashCap" Value="Triangle" />
</Style>
</Window.Resources>
<Viewbox>
<Canvas Width="200" Height="200">
<Canvas.RenderTransform>
<TranslateTransform X="100" Y="100" />
</Canvas.RenderTransform>
<Path Data="M 0 -90 A 90 90 0 1 1 -0.01 -90"
StrokeDashArray="0 3.14157" />
<Path Data="M 0 -90 A 90 90 0 1 1 -0.01 -90"
StrokeDashArray="0 7.854"
StrokeThickness="6" />
<Border Background="LightBlue" Width="10" Height="80" RenderTransformOrigin="0.5 0">
<Border.RenderTransform>
<TransformGroup>
<RotateTransform x:Name="bor_Second"
Angle="{Binding Source={StaticResource transformSecond},Path=Value.OffsetX}" />
<RotateTransform Angle="180" />
</TransformGroup>
</Border.RenderTransform>
</Border>
<Border Background="LightGreen" Width="10" Height="60" RenderTransformOrigin="0.5 0">
<Border.RenderTransform>
<TransformGroup>
<RotateTransform x:Name="bor_Minute"
Angle="{Binding Source={StaticResource transformMinute},Path=Value.OffsetX}" />
<RotateTransform Angle="180" />
</TransformGroup>
</Border.RenderTransform>
</Border>
<Border Background="LightGray" Width="10" Height="40" RenderTransformOrigin="0.5 0">
<Border.RenderTransform>
<TransformGroup>
<RotateTransform x:Name="bor_Hour"
Angle="{Binding Source={StaticResource transformHour},Path=Value.OffsetX}" />
<RotateTransform Angle="180" />
</TransformGroup>
</Border.RenderTransform>
</Border>
</Canvas>
</Viewbox>
<Window.Triggers>
<EventTrigger RoutedEvent="Loaded">
<BeginStoryboard>
<Storyboard>
<DoubleAnimation Storyboard.TargetName="bor_Hour"
Storyboard.TargetProperty="Angle"
IsAdditive="True"
Duration="12:0:0"
From="0" To="360"
RepeatBehavior="Forever" />
<DoubleAnimation Storyboard.TargetName="bor_Minute"
Storyboard.TargetProperty="Angle"
IsAdditive="True"
Duration="1:0:0"
From="0" To="360"
RepeatBehavior="Forever" />
<DoubleAnimation Storyboard.TargetName="bor_Second"
Storyboard.TargetProperty="Angle"
IsAdditive="True"
Duration="0:1:0"
From="0"
To="360"
RepeatBehavior="Forever" />
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</Window.Triggers>
</Window>
Create a clock using only xaml code in wpf

Type reference cannot find type named '{clr-namespace:xxx}ClassName on MergedDictionary

I'm received the exception Type reference cannot find type named '{clr-namespace:Dashboard.View}DashBoardColors at runtime.
I have a static class with my colors:
namespace Dashboard.View
{
public static class DashBoardColors
{
public static readonly Color TargetColor = Color.FromRgb(200, 240, 255);
public static readonly SolidColorBrush Red = new SolidColorBrush(Color.FromRgb(255, 0, 0));
public static readonly SolidColorBrush Stale = new SolidColorBrush(Color.FromRgb(200, 200, 200));
public static readonly SolidColorBrush Target = new SolidColorBrush(TargetColor);
public static readonly SolidColorBrush Dragging = new SolidColorBrush(Color.FromRgb(200, 255, 200));
public static readonly SolidColorBrush Good = Dragging;
}
}
My resource dictionary:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:view="clr-namespace:Dashboard.View">
<Style x:Key="AnimatedSwitch" TargetType="{x:Type ToggleButton}">
<Setter Property="Foreground" Value="Silver" />
<Setter Property="Background" Value="Silver" />
<Setter Property="BorderBrush" Value="Silver" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ToggleButton">
<Viewbox Stretch="Uniform" Width="40">
<Canvas Name="Layer_1" Width="20" Height="20">
<Ellipse Canvas.Left="0" Width="20" Height="20" Fill="{TemplateBinding Background}" Stroke="{TemplateBinding BorderBrush}" StrokeThickness="0.5"/>
<Ellipse Canvas.Left="15" Width="20" Height="20" Fill="{TemplateBinding Background}" Stroke="{TemplateBinding BorderBrush}" StrokeThickness="0.5"/>
<Border Canvas.Left="10" Width="15" Height="20" Name="rect416927" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="0,0.5,0,0.5"/>
<Ellipse x:Name="ellipse" Canvas.Left="0" Width="20" Height="20" Fill="White" Stroke="{TemplateBinding BorderBrush}" StrokeThickness="0.3">
<Ellipse.RenderTransform>
<TranslateTransform X="0" Y="0" />
</Ellipse.RenderTransform>
<Ellipse.BitmapEffect>
<DropShadowBitmapEffect Softness="0.1" ShadowDepth="0.7" Direction="270" Color="#BBBBBB"/>
</Ellipse.BitmapEffect>
</Ellipse>
</Canvas>
</Viewbox>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Trigger.EnterActions>
<BeginStoryboard>
<Storyboard>
<ColorAnimation Duration="0:0:0.15"
Storyboard.TargetName="ellipse"
Storyboard.TargetProperty="(Shape.Fill).(SolidColorBrush.Color)"
To="{x:Static view:DashBoardColors.TargetColor}" />
</Storyboard>
</BeginStoryboard>
</Trigger.EnterActions>
<Trigger.ExitActions>
<BeginStoryboard>
<Storyboard FillBehavior="Stop">
<ColorAnimation Duration="0:0:0.3"
Storyboard.TargetName="ellipse"
Storyboard.TargetProperty="(Shape.Fill).(SolidColorBrush.Color)"
To="White" />
</Storyboard>
</BeginStoryboard>
</Trigger.ExitActions>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
And my usage within the usercontrol:
Included the namespace:
xmlns:view="clr-namespace:Dashboard.View"
Merged the dictionary:
<UserControl.Resources>
<ResourceDictionary x:Key="Styles">
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="pack://application:,,,/Dashboard;component/View/Styles/AnimatedStyles.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</UserControl.Resources>
Applied the style:
<ToggleButton Style="{StaticResource AnimatedSwitch}" Height="20" x:Name="DateSelectToggle" />
The problem is in setting the following:
To="{x:Static view:DashBoardColors.TargetColor}"
Oops,
I had the build action on View/Styles/AnimatedStyles.xaml set to resource which means that namespace needed to include the assembly, if it is not current:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:view="clr-namespace:Dashboard.View;assembly=Dashboard">
Or set the build action to Page and now it works.

C# WPF Ellipse Slider

I just want to know if there is a way on how to make an ellipse slider with thumb like this one example I made in paint:
Right now I am using a style but only works on horizontal silders. Here is the sample code:
<Style x:Key="SliderRepeatButton" TargetType="RepeatButton">
<Setter Property="SnapsToDevicePixels" Value="true"/>
<Setter Property="OverridesDefaultStyle" Value="true"/>
<Setter Property="IsTabStop" Value="false"/>
<Setter Property="Focusable" Value="false" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="RepeatButton">
<Border Height="4" >
<Border.Background>
<ImageBrush ImageSource="/FoodWare;component/Resources/draggerLine.png"></ImageBrush>
</Border.Background>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style x:Key="SliderRepeatButton1" TargetType="RepeatButton">
<Setter Property="Focusable" Value="false" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="RepeatButton">
<Border Height="4">
<Border.Background>
<ImageBrush ImageSource="/FoodWare;component/Resources/draggerFull.png"></ImageBrush>
</Border.Background>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style x:Key="SliderThumb" TargetType="Thumb">
<Setter Property="SnapsToDevicePixels" Value="true"/>
<Setter Property="OverridesDefaultStyle" Value="true"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Thumb">
<Ellipse Height="10" Width="10" Margin="0" StrokeThickness="0" StrokeDashArray="0" StrokeMiterLimit="0" StrokeLineJoin="Round">
<Ellipse.Fill>
<ImageBrush ImageSource="/FoodWare;component/Resources/draggerBtn1.png" ></ImageBrush>
</Ellipse.Fill>
</Ellipse>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<ControlTemplate x:Key="Slider" TargetType="Slider">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" MinHeight="{TemplateBinding MinHeight}" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Track Grid.Row="1" x:Name="PART_Track" >
<Track.DecreaseRepeatButton>
<RepeatButton Style="{StaticResource SliderRepeatButton1}" Command="Slider.DecreaseLarge" />
</Track.DecreaseRepeatButton>
<Track.Thumb>
<Thumb Style="{StaticResource SliderThumb}" />
</Track.Thumb>
<Track.IncreaseRepeatButton>
<RepeatButton Style="{StaticResource SliderRepeatButton}" Command="Slider.IncreaseLarge" />
</Track.IncreaseRepeatButton>
</Track>
</Grid>
</ControlTemplate>
<Style x:Key="Horizontal_Slider" TargetType="Slider">
<Setter Property="Focusable" Value="False"/>
<Style.Triggers>
<Trigger Property="Orientation" Value="Horizontal">
<Setter Property="Template" Value="{StaticResource Slider}" />
</Trigger>
</Style.Triggers>
</Style>
If I try to replace the image with circle images, the circle is cut to a semi-circle and the slider moves horizontally. I'll be glad to here your answer. Thanks.
How about using a Rotating thumb, this isn't working 100%, but you should be able to get it from here, basically this draws a rectangle and allows you to rotate it. You could rotate the image you showed in your question, this would appear to be a slider, but really your just rotating an image. The broken part is the rotatethumb class is rotating the rectangle around the lower left corner instead of the center which is what you would want
Xaml:
<Canvas>
<Canvas.Resources>
<ControlTemplate x:Key="MoveThumbTemplate" TargetType="{x:Type local:RotateThumb}">
<Rectangle Fill="Transparent"/>
</ControlTemplate>
<ControlTemplate x:Key="DesignerItemTemplate" TargetType="Control">
<Grid>
<local:RotateThumb Template="{StaticResource MoveThumbTemplate}"
DataContext="{Binding RelativeSource={RelativeSource TemplatedParent}}"
Cursor="SizeAll"/>
<ContentPresenter Content="{TemplateBinding ContentControl.Content}"/>
</Grid>
</ControlTemplate>
</Canvas.Resources>
<ContentControl Name="DesignerItem"
Width="100"
Height="100"
Canvas.Top="100"
Canvas.Left="100"
Template="{StaticResource DesignerItemTemplate}">
<Rectangle Fill="Blue" IsHitTestVisible="False"/>
</ContentControl>
</Canvas>
Thumb subclass:
public class RotateThumb : Thumb
{
private double initialAngle;
private RotateTransform rotateTransform;
private Vector startVector;
private Point centerPoint;
private ContentControl designerItem;
private Canvas canvas;
public RotateThumb()
{
DragDelta += new DragDeltaEventHandler(this.RotateThumb_DragDelta);
DragStarted += new DragStartedEventHandler(this.RotateThumb_DragStarted);
}
private void RotateThumb_DragStarted(object sender, DragStartedEventArgs e)
{
this.designerItem = DataContext as ContentControl;
if (this.designerItem != null)
{
this.canvas = VisualTreeHelper.GetParent(this.designerItem) as Canvas;
if (this.canvas != null)
{
this.centerPoint = this.designerItem.TranslatePoint(
new Point(this.designerItem.Width * this.designerItem.RenderTransformOrigin.X,
this.designerItem.Height * this.designerItem.RenderTransformOrigin.Y),
this.canvas);
Point startPoint = Mouse.GetPosition(this.canvas);
this.startVector = Point.Subtract(startPoint, this.centerPoint);
this.rotateTransform = this.designerItem.RenderTransform as RotateTransform;
if (this.rotateTransform == null)
{
this.designerItem.RenderTransform = new RotateTransform(0);
this.initialAngle = 0;
}
else
{
this.initialAngle = this.rotateTransform.Angle;
}
}
}
}
private void RotateThumb_DragDelta(object sender, DragDeltaEventArgs e)
{
if (this.designerItem != null && this.canvas != null)
{
Point currentPoint = Mouse.GetPosition(this.canvas);
Vector deltaVector = Point.Subtract(currentPoint, this.centerPoint);
double angle = Vector.AngleBetween(this.startVector, deltaVector);
RotateTransform rotateTransform = this.designerItem.RenderTransform as RotateTransform;
rotateTransform.Angle = this.initialAngle + Math.Round(angle, 0);
this.designerItem.InvalidateMeasure();
}
}
}
This was adapted from sukram's WPF Diagram Designer article on code project

Attach Dependency Property to User Control

How to register DependencyProperty on Rectangle fill, so i can change the color
dynamically?
<UserControl.Resources>
<Style x:Key="ButtonStyle1" TargetType="{x:Type Button}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Grid>
<Rectangle Stroke="Black">
<Rectangle.Fill>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="#FF48B6E4" Offset="0.013"/>
<GradientStop Color="#FF091D8D" Offset="1"/>
</LinearGradientBrush>
</Rectangle.Fill>
</Rectangle>
<ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
</Grid>
<ControlTemplate.Triggers>
<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>
</Style>
</UserControl.Resources>
<Grid x:Name="LayoutRoot">
<Button Style="{DynamicResource ButtonStyle1}"/>
<TextBlock
x:Name="NodeName"
x:FieldModifier="public"
Text="Property"
Margin="8"
HorizontalAlignment="Center"
VerticalAlignment="Center"
TextWrapping="Wrap"
TextAlignment="Center"
FontFamily="Segoe Print"
FontWeight="Bold"
Foreground="White"
FontSize="40"/>
</Grid>
Why don't you bind Fill to the Background property of the Button:
<ControlTemplate TargetType="{x:Type Button}">
<Grid>
<Rectangle Stroke="Black" Fill="{TemplateBinding Background}" />
...
</Grid>
...
</ControlTemplate>
and then set Background like this:
<Button Style="{DynamicResource ButtonStyle1}">
<Button.Background>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="#FF48B6E4" Offset="0.013"/>
<GradientStop Color="#FF091D8D" Offset="1"/>
</LinearGradientBrush>
</Button.Background>
</Button>
If you have your own dependency property called MyProperty registered in your UserControl, you can bind it this way:
...
<Rectangle Stroke="Black" Fill="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Parent.Parent.MyProperty}" />
...
No other changes are needed.
This binds the Fill property to parent of parent of the control to which the style is assigned, in your case the UserControl itself.
Using this method you can not only bind it to properties of a UserControl, but also to other controls' properties.
I would create a dependency property on your YourUserControl view, something like this (I removed some of your markup for brevity):
<UserControl.Resources>
<Style x:Key="ButtonStyle1" TargetType="{x:Type Button}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Grid>
<Rectangle Stroke="Black" Fill="{TemplateBinding Background}">
</Rectangle>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Grid x:Name="LayoutRoot">
<Button Style="{DynamicResource ButtonStyle1}" Background="{Binding DynamicColor}"/>
</Grid>
Then in YourUserControl.xaml.cs you could create your dependency property:
private My_ViewModel _viewModel
{
get { return this.DataContext as My_ViewModel; }
}
public LinearGradientBrush DynamicColor
{
get { return (string)GetValue(DynamicColorProperty); }
set { SetValue(DynamicColorProperty, value); }
}
public static readonly DependencyProperty DynamicColorProperty =
DependencyProperty.Register("DynamicColor", typeof(LinearGradientBrush), typeof(YourUserControl),
new PropertyMetadata(new PropertyChangedCallback(OnDynamicColorPropertyChanged)));
private static void OnDynamicColorPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
((YourUserControl)d).OnTrackerInstanceChanged(e);
}
protected virtual void OnDynamicColorPropertyChanged(DependencyPropertyChangedEventArgs e)
{
this._viewModel.DynamicColor = e.NewValue;
}
public class My_ViewModel : INotifyPropertyChanged
{
public LinearGradientBrush DynamicColor
{
get { return dynamicColor; }
set
{
if(dynamicColor != value)
{
dynamicColor = value;
OnPropertyChanged("DynamicColor");
}
}
}
private LinearGradientBrush dynamicColor;
}
This approach gives you complete control over the DynamicColor property's value as well as allows you to be able to unit test the behavior effectively.

Replicating standard system menu with WindowChrome?

When using WindowChrome (downloadable here) to customize the nonclient area of a window, a natural starting point is to make a title bar that looks and acts identical to a standard title bar. This requires adding a "fake" application icon and title bar, because apparently WindowChrome disables those features (the minimize, maximize and close buttons still work.)
Here's what I have so far:
<Window x:Class="MyApp.MainWindow"
x:Name="MainWindowItself"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:shell="clr-namespace:Microsoft.Windows.Shell;assembly=Microsoft.Windows.Shell"
xmlns:local="clr-namespace:MyApp"
Title="My Application" Icon="App.ico" Height="350" Width="525">
<Window.Resources>
<Style TargetType="{x:Type local:MainWindow}">
<Setter Property="shell:WindowChrome.WindowChrome">
<Setter.Value>
<shell:WindowChrome />
</Setter.Value>
</Setter>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:MainWindow}">
<Grid>
<Border Background="White" Margin="{Binding Source={x:Static shell:SystemParameters2.Current}, Path=WindowNonClientFrameThickness}">
<ContentPresenter Content="{TemplateBinding Content}" />
</Border>
<TextBlock Text="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Title}"
VerticalAlignment="Top" HorizontalAlignment="Left"
Margin="32,8,0,0"/>
<Image x:Name="SystemMenuIcon" Source="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Icon}"
VerticalAlignment="Top" HorizontalAlignment="Left"
Margin="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=(shell:WindowChrome.WindowChrome).ResizeBorderThickness}"
Width="{Binding Source={x:Static shell:SystemParameters2.Current}, Path=SmallIconSize.Width}"
shell:WindowChrome.IsHitTestVisibleInChrome="True" MouseDown="SystemMenuIcon_MouseDown">
</Image>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
<Grid>
<TextBlock Text="Client area content goes here"/>
</Grid>
</Window>
Code behind:
private void SystemMenuIcon_MouseDown(object sender, MouseButtonEventArgs e)
{
var offs = SystemParameters2.Current.WindowNonClientFrameThickness;
SystemCommands.ShowSystemMenu(this, new Point(Left + offs.Left, Top + offs.Top));
}
This comes very close to working. The first problem is that after you click the application icon and the system menu appears, the menu should disappear if you click a second time--instead, the menu just redraws. Also, if you double-click then the window should close, but Image doesn't have a double-click event. How would you suggest adding these features?
To disable working of standard Chrome Buttons Just add an extra attribute CaptionHeight="0" in your XAML code of shell:WindowsChrome
So it will be like that
<Setter Property="shell:WindowChrome.WindowChrome">
<Setter.Value>
<shell:WindowChrome CaptionHeight="0" />
</Setter.Value>
</Setter>
To make a fake Chrome. Modify the Template to like this:
<ControlTemplate TargetType="Window">
<AdornerDecorator>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="35" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Grid x:Name="PART_Chrome" shell:WindowChrome.IsHitTestVisibleInChrome="True">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="50" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="105" />
</Grid.ColumnDefinitions>
<Image Source="Application Favicon Path" />
<TextBlock Grid.Column="1" Text="{TemplateBinding Title}" VerticalAlignment="Center" />
<StackPanel Orientation="Horizontal" Grid.Column="3" >
<Button Command="{Binding Source={x:Static shell:SystemCommands.MinimizeWindowCommand}}" >
<Path Data="M0,6 L8,6 Z" Width="8" Height="7" VerticalAlignment="Center" HorizontalAlignment="Center"
Stroke="{Binding Foreground, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Button}}" StrokeThickness="2" />
</Button>
<Button x:Name="MaximizeButton" Command="{Binding Source={x:Static shell:SystemCommands.MaximizeWindowCommand}}" >
<Path Data="M0,1 L9,1 L9,8 L0,8 Z" Width="9" Height="8" VerticalAlignment="Center" HorizontalAlignment="Center"
Stroke="{Binding Foreground, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Button}}" StrokeThickness="2" />
</Button>
<Button x:Name="RestoreButton" Command="{Binding Source={x:Static shell:SystemCommands.RestoreWindowCommand}}" >
<Path Data="M2,0 L8,0 L8,6 M0,3 L6,3 M0,2 L6,2 L6,8 L0,8 Z" Width="8" Height="8" VerticalAlignment="Center" HorizontalAlignment="Center"
Stroke="{Binding Foreground, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Button}}" StrokeThickness="1" />
</Button>
<Button Command="{Binding Source={x:Static shell:SystemCommands.CloseWindowCommand}}" >
<Path Data="M0,0 L8,7 M8,0 L0,7 Z" Width="8" Height="7" VerticalAlignment="Center" HorizontalAlignment="Center"
Stroke="{Binding Foreground, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Button}}" StrokeThickness="1.5" />
</Button>
</StackPanel>
</Grid>
<ContentPresenter Grid.Row="1" Content="{TemplateBinding Content}" />
</Grid>
</AdornerDecorator>
<ControlTemplate.Triggers>
<Trigger Property="WindowState" Value="Normal">
<Setter Property="Visibility" Value="Collapsed" TargetName="RestoreButton" />
<Setter Property="Visibility" Value="Visible" TargetName="MaximizeButton" />
</Trigger>
<Trigger Property="WindowState" Value="Maximized">
<Setter Property="Visibility" Value="Visible" TargetName="RestoreButton" />
<Setter Property="Visibility" Value="Collapsed" TargetName="MaximizeButton" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
Also do command binding for proper working of Fake Chrome bar
public MainWindow()
{
this.CommandBindings.Add(new CommandBinding(SystemCommands.CloseWindowCommand, OnCloseWindow));
this.CommandBindings.Add(new CommandBinding(SystemCommands.MaximizeWindowCommand, OnMaximizeWindow, OnCanResizeWindow));
this.CommandBindings.Add(new CommandBinding(SystemCommands.MinimizeWindowCommand, OnMinimizeWindow, OnCanMinimizeWindow));
this.CommandBindings.Add(new CommandBinding(SystemCommands.RestoreWindowCommand, OnRestoreWindow, OnCanResizeWindow));
}
private void OnCanMinimizeWindow(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = this.ResizeMode != ResizeMode.NoResize;
}
private void OnCanResizeWindow(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = this.ResizeMode == ResizeMode.CanResize || this.ResizeMode == ResizeMode.CanResizeWithGrip;
}
private void OnCloseWindow(object sender, ExecutedRoutedEventArgs e)
{
Microsoft.Windows.Shell.SystemCommands.CloseWindow(this);
}
private void OnMaximizeWindow(object sender, ExecutedRoutedEventArgs e)
{
Microsoft.Windows.Shell.SystemCommands.MaximizeWindow(this);
}
private void OnMinimizeWindow(object sender, ExecutedRoutedEventArgs e)
{
Microsoft.Windows.Shell.SystemCommands.MinimizeWindow(this);
}
private void OnRestoreWindow(object sender, ExecutedRoutedEventArgs e)
{
Microsoft.Windows.Shell.SystemCommands.RestoreWindow(this);
}
My xaml is not exactly alike (I do not use WindowChrome but my own and I have a titlebar template), but I had the exact same problem and the solution should be usable for you as well.
First the easy one: for the doubleclick to work just use the ClickCount.
Then, geting the menu disappear requires keeping some state telling whether it is currently active or not: the trick is that different events are fired on the second click (as figured out by using Snoop. The first click is only a MousweDown, the second is MouseDown followed by MouseUp (my guess is that the up from the first click is handled by the sysmenu).
private bool inSysMenu = false;
void SystemMenuIcon_MouseDown( object sender, MouseButtonEventArgs e )
{
if( e.ClickCount == 1 && !inSysMenu )
{
inSysMenu = true;
ShowSystemMenu(); //replace with your code
}
else if( e.ClickCount == 2 && e.ChangedButton == MouseButton.Left )
{
window.Close();
}
}
void SystemMenuIcon_MouseLeave( object sender, MouseButtonEventArgs e )
{
inSysMenu = false;
}
void SystemMenuIcon_MouseUp( object sender, MouseButtonEventArgs e )
{
inSysMenu = false;
}

Categories