WPF custom control library - c#

I am trying to build a custom control which has button and text. When i am trying to compile i am getting the following error.
Error 1 'ResourceDictionary' root element requires a x:Class attribute to support event handlers in the XAML file. Either remove the event handler for the Click event, or add a x:Class attribute to the root element.
My Code :
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:textbtn">
<Style TargetType="{x:Type local:CustomControl1}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:CustomControl1}">
<Border Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
<Grid>
<TextBlock Text="This is a Test" Foreground="Aqua" Background="AntiqueWhite"/>
<Button Content="Button" Height="23" HorizontalAlignment="bottom" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click" />
</Grid>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>

The error means exactly what it says. The click event handler actually does the following:
myButtonName.Click += myClass.ClickHandlerName;
If you don't have a class assigned to the resource dictionary, it doesn't know what to assign the click handler to!
Because a control template shouldn't be tightly coupled to a specific class in the code behind, I would remove the click handler from the template entirely. Command is a better choice in MVVM anyways.

The error is well explained by LordTakkera, but he doesn't want the simple solution to be appened to his answer, so, to clear the point, Providing a Class Name to the resource dictionary will allow you to use event handler as in other controls:
<ResourceDictionary
x:Class="ResourceDictionaryClass1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:textbtn">
But indeed is LordTakkera right: Commands are a clean way of implementing ui callbacks.

Related

Disable WPF Button Hover Effect

The standard WPF Button control has a mouseover highlight that changes the colour of the control. I'm trying to disable this effect. Whilst I see lots of questions and answers to this on SO that involve changes to XAML, I'm trying to do this 100% programmatically, and I haven't been able to find any solution to this problem.
I don't have any XAML, as my WPF app dynamically adds a list of (derived) button controls to the form. The derived button class has no XAML whatsoever.
var button = new CustomButton(); // Inherits System.Windows.Controls.Button
button.Content = textBlock; // System.Windows.Controls.TextBlock
// other various property changes to the custom button removed
button.Focusable = false;
grid.Children.Add(button);
The button works perfectly with my custom code, but I just can't remove the mouseover effect. This is particularly bad, as it's being used on a touch screen, so the last touched button retains the mouseover effect until another button is pressed or the user clicks an unused area of the window.
Thanks to Kostas in the comments, I now know I need to create a global style and apply this to my custom control, however as per my original question, all the examples of doing this involve XAML, so my question really ought to be more specifically, how can I create a global style without a mouse over trigger, entirely programmatically?
The piece of the puzzle I was missing, was that the XAML for the style doesn't need to go in the button class, it instead goes into the parent window XAML. The Style is then added to the button class as it's added to the Window:
<Window x:Class="SomeOrg.SomeApp.WpfInterface.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfInterface"
mc:Ignorable="d"
Title="SomeApp" Height="450" Width="800"
Background="#ffffffe1">
<Window.Resources>
<Style x:Key="MyButton" TargetType="Button">
<Setter Property="OverridesDefaultStyle" Value="True" />
<Setter Property="Cursor" Value="Hand" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Border Name="border" BorderThickness="0" BorderBrush="Black" Background="{TemplateBinding Background}">
<ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" />
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
<Grid>
<Grid x:Name="grid" HorizontalAlignment="Stretch" Height="Auto" Margin="10,10,10,10" VerticalAlignment="Stretch"
Width="Auto" Background="#ffffffe1"/>
</Grid>
</Window>
In the parent window's code, where the custom button is added to the window, the above style (MyButton), is applied as follows:
var button = new CustomButton();
customButton.Style = (Style) this.Resources["MyButton"];
grid.Children.Add(button);

Bind to Application.ActualTheme in a ControlTemplate XAML UWP

I'm trying to create a control that uses a RevealBorderBrush as its border brush in XAML. I want to use the correct TargetTheme value for the brush, so I'm trying to bind to my application's current ActualTheme value. I'm using a templated control to do this. My C# code behind file is just the empty constructor that inherits from Control and sets the default style key. The following is my Generic.xaml
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:Plank">
<Style TargetType="local:PlankPL" >
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="local:PlankPL">
<Border
Background="{TemplateBinding Background}"
BorderThickness="{TemplateBinding BorderThickness}">
<Border.BorderBrush>
<RevealBorderBrush TargetTheme="{Binding Source=local:App, Path=ActualTheme}"/>
</Border.BorderBrush>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
I'm pretty sure the binding statement is incorrect, but I'm not sure how to write it.
I haven't tested this but it should work. Name your control then use the below code, replace ControlTemplateName with what you used.
You can’t bind background data in ResourceDictionary, it doesn’t work.
It is recommended to write a UserControl and bind the RevealBorderBrush property of Border like following.
MyUserControl1.xaml:
<UserControl..>
<StackPanel>
<Border BorderThickness="3">
<Border.BorderBrush>
<RevealBorderBrush TargetTheme="{x:Bind theme1}"/>
</Border.BorderBrush>
</Border>
<TextBox Text = "text demo text "/>
</StackPanel>
</UserControl>
MyUserControl1.xaml.cs:
public sealed partial class MyUserControl1 : UserControl
{
private ApplicationTheme theme1;
public MyUserControl1()
{
this.InitializeComponent();
theme1 = Application.Current.RequestedTheme;
}
}

How to access UI control from code-behind of ResourceDictionary

So I have a ResourceDictionary to define my custom Window style. What I am struggling to do is to access controls from XAML file.
The ResourceDictionary looks like this
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Style x:Key="MyCustomWindowStyle" TargetType="{x:Type Window}">
<Setter Property="WindowChrome.WindowChrome">
<Setter.Value>
<WindowChrome CaptionHeight="30"/>
</Setter.Value>
</Setter>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Window}">
<Grid>
<!-- the root window -->
<Border BorderThickness="0.3" BorderBrush="{DynamicResource GeneralDarkBlue}">
<AdornerDecorator>
<ContentPresenter />
</AdornerDecorator>
</Border>
<DockPanel Height="30" Background="{TemplateBinding Background}" VerticalAlignment="Top" LastChildFill="False">
<Viewbox x:Name="HamburgerMenu" DockPanel.Dock="Left" WindowChrome.IsHitTestVisibleInChrome="True">
<Viewbox.InputBindings>
<MouseBinding MouseAction="LeftClick" Command="{Binding SettingsClick}"/>
</Viewbox.InputBindings>
<Border Width="47" Height="32" Background="Transparent">
<Canvas>
<Path x:Name="TopbarIconHamburgerMenu" Margin="14,10" Data="M12.5,19h19.2v1H12.5V19z M12.5,13.7h19.2v1H12.5V13.7z M12.5,8.5h19.2v1H12.5V8.5z" Stretch="UniformToFill" Fill="#FFFFFF"/>
</Canvas>
</Border>
</Viewbox>
// the rest of viewboxes for minimize, maximize controls...
</DockPanel>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
And let's say I want to access the HamburgerMenu, so I do something like this
public partial class MyCustomWindowStyle : ResourceDictionary
{
public MyCustomWindowStyle()
{
InitializeComponent();
}
public void DoSomething()
{
var window = (Style)Application.Current.Resources["MyCustomWindowStyle"];
var hm = (Viewbox)window.Resources.FindName("HamburgerMenu");
}
}
and this returns null in the hm!
Any idea how to do this?
First of all, Style.Resource is a ResourceDictionary, and there are two important things to notice in the ResourceDictionary.FindName method documentation:
Summary section saying:
Not supported by this Dictionary implementation.
and Return Value section saying:
Always returns null.
Second of all, even if you tried to retrieve the ViewBox by key, it would have to be defined as a resource:
<Style x:Key="MyCustomWindowStyle" TargetType="{x:Type Window}">
<Style.Resources>
<ViewBox x:Key="HamburgerMenu" />
</Style.Resources>
</Style>
And it is not. It is a part of ControlTemplate's visual tree.
Third of all, ControlTemplate does not contain actual elements, but rather a recipe for creating them. So there's no actual ViewBox living inside the ControlTemplate to retrieve. Notice that ControlTemplate.FindName takes an additional parameter specifying an element for which the template was realized.
However, ControlTemplate does have a LoadContent method, which basically loads the visual tree defined by that template, and I think you could use it, and then invoke FindName on the root element. To simplify retrieval of the ControlTemplate let's first make it a resource:
<Style x:Key="MyCustomWindowStyle" TargetType="{x:Type Window}">
<Style.Resources>
<ControlTemplate x:Key="Template" TargetType="{x:Type Window}">
<Grid>
(...)
<ViewBox x:Key="HamburgerMenu" />
(...)
</Grid>
</ControlTemplate>
</Style.Resources>
<Setter Property="Template" Value="{StaticResource Template}" />
</Style>
Then this should do the trick for you:
var window = (Style)Application.Current.Resources["MyCustomWindowStyle"];
var template = (ControlTemplate)window.Resources["Template"];
var root = (FrameworkElement)template.LoadContent();
var hm = (ViewBox)root.FindName("HamburgerMenu");
Update
If your goal is to get hold of the ViewBox in an existing window with that template applied, first you need to know how to get hold of that particular window. It could be the Application.Current.MainWindow, otherwise you're highly likely to find it in the Application.Current.Windows collection. You could also implement the singleton pattern for that window, or use other methods like exposing a static property with reference to that window somewhere in your application, or using third-party tools, such as Service Locator in Prism.
Once you have the window in your hand, you only need to use the previously mentioned ControlTemplate.FindName method:
var window = (...);
var hm = (ViewBox)window.Template.FindName(name: "HamburgerMenu", templatedParent: window);
Note that accessing the resource dictionary in which the template was defined is not necessary.
As for why your attempts with previous solution failed - that's because ControlTemplate.LoadContent method yields freshly created element each time it is invoked, and modifying it does not reflect on elements previously created by that template.

Border Margin in Window template doesn't have any effect when used with WindowChrome

I was checking out the WindowChrome class in System.Windows.Shell library (v 3.5.41019.1). When I try to create a Window template, the margin of the Border element in the template seems to have no effect:
<Window x:Class="WpfApplication7.MainWindow"
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"
Title="MainWindow" Height="350" Width="525" Style="{DynamicResource WindowStyle1}">
<Window.Resources>
<Style x:Key="WindowStyle1" TargetType="{x:Type Window}">
<!-- Here is the WindowChrome.-->
<Setter Property="shell:WindowChrome.WindowChrome">
<Setter.Value>
<shell:WindowChrome />
</Setter.Value>
</Setter>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Window}">
<!-- And here is the Border. Its margin has no effect as far as I can tell.-->
<Border Margin="25" Background="Red">
<AdornerDecorator>
<ContentPresenter/>
</AdornerDecorator>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
<Grid>
</Grid>
</Window>
What do you think is the reason for that? I am wondering that, because I saw that some people use something like*:
<Border x:Name="WindowBorder" Margin="{Binding Source={x:Static shell:SystemParameters2.Current}, Path=WindowNonClientFrameThickness}" Background="Red">
But as it doesn't have any effect in my tests, what could be the point of doing this?
(*) One of the places it is used is the ModernUI project on CodePlex.
Edit: I have tested this on Windows 7 with Aero on.
Edit 2: It's still the same with Aero off.
According to MSDN, WindowChrome is
Represents an object that describes the customizations to the non-client area of a window.
After reading MSDN sample and playing your code a while, I noticed your code should be like following from MSDN sample code:
<Style x:Key="StandardStyle" 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}">
<!--Note there is a Grid as the root-->
<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="36,8,0,0"/>
<Image 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"/>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
Note, there's a Grid as the root element which contains a few elements for customizing the NC of the window.
UPDATE:
You may notice in the remark of the MSDN page, it contains sections:
WindowStyle.None
WindowChrome
These are the two ways of customizing the appearance of a WPF application window.
However, setting the Window.WindowStyle property to WindowStyle.None:
This removes the non-client frame from the window and leaves only the
client area, to which you can apply a custom style. However, when the
non-client frame is removed, you also lose the system features and
behaviors that it provides, such as caption buttons and window
resizing. Another side effect is that the window will cover the
Windows taskbar when it is maximized.
Then WindowChrome is introduced to enable NC customization using WPF:
To customize a window while retaining its standard functionality, you
can use the WindowChrome class. The WindowChrome class separates the
functionality of the window frame from the visuals, and lets you
control the boundary between the client and non-client areas of your
application window. The WindowChrome class lets you put WPF content in
the window frame by extending the client area to cover the non-client
area. At the same time, it retains system behaviors through two
invisible areas; the resize border and caption areas.
So back to your question, the template you found, should be copied from the MSDN sample code, but missed the true root Grid.
The Margin on the Border is for giving some space to the NC.
In the MSDN sample code, the ContenPreseter only contains the Client area, while the NC contains the Border, a TextBlock for window title, and an Image for window icon.
To recap, setting WindowChrome enables you to customize the NC area of the window in the Window.Template.
NOTE:
The sample MSDN sample code seems a little out of date in .Net 4.5, the System.Windows.Shell.WindowChrome is now in the PresentationFramework.dll, so the code may look like:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525" Style="{DynamicResource WindowStyle1}" Icon="Icon1.ico">
<Window.Resources>
<Style x:Key="WindowStyle1" TargetType="{x:Type Window}">
<Setter Property="WindowChrome.WindowChrome">
<Setter.Value>
<WindowChrome />
</Setter.Value>
</Setter>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Window}">
<Grid>
<Border Background="Red"
Margin="{Binding Source={x:Static SystemParameters.WindowNonClientFrameThickness}}">
<ContentPresenter Content="{TemplateBinding Content}" />
</Border>
<TextBlock Text="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Title}"
VerticalAlignment="Top" HorizontalAlignment="Left"
Margin="36,8,0,0"/>
<Image Source="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Icon}"
VerticalAlignment="Top" HorizontalAlignment="Left"
Margin="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=WindowChrome.WindowChrome.ResizeBorderThickness}"
Width="{Binding Source={x:Static SystemParameters.SmallIconWidth}}"
WindowChrome.IsHitTestVisibleInChrome="True"/>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
<Grid>
<Button />
</Grid>
I think there is some misunderstanding in the way you are trying to set the border. Here is the explanation of WindowChrome Class as provided in msdn
The WindowChrome class separates the functionality of the window frame from the visuals, and lets you control the boundary between the client and non-client areas of your application window. The WindowChrome class lets you put WPF content in the window frame by extending the client area to cover the non-client area. At the same time, it retains system behaviors through two invisible areas; the resize border and caption areas.
So if you are trying to customize the NonClient Area of the Window, its not the Content Presenter that you should set Border onto. That is the client area. Instead in the Template you can add your XAML other than Content Presenter to define your NonClient Area. I just tried a simple code based on your code and it shifts the Title Property of the Window to the right by a value of 100. Here is the code.
<Window x:Class="WPF_ToggleButton.ShellWindow"
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"
Title="MainWindow" Height="350" Width="525" Style="{DynamicResource WindowStyle1}"
>
<Window.Resources>
<Style x:Key="WindowStyle1" TargetType="{x:Type Window}">
<Setter Property="shell:WindowChrome.WindowChrome">
<Setter.Value>
<shell:WindowChrome />
</Setter.Value>
</Setter>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Window}">
<Grid>
<Border Background="Yellow">
<AdornerDecorator>
<ContentPresenter Content="{TemplateBinding Content}"/>
</AdornerDecorator>
</Border>
<TextBlock Text="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Title}"
VerticalAlignment="Top" HorizontalAlignment="Left"
Margin="100,0,0,0"/>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
<Grid>
<Border Margin="50" Background="AliceBlue"/>
</Grid>
Thus you can have any elements in the NonClient Area like image representing your Window Close Button, etc using XAML code. The last element in the Window defines the Client Area which is passed to the Content Presenter in the Template
In short if you wan't to customize Client Area use the Content Presenter, whereas if you are interested in changing the NonClient Area like Title Bar display, close image icon then you define it in the Template.
One short observation. I think Margin doesn't make any sense for a Window. Try setting it for a normal window and I think it won't respect it.
Run into the same problem. No matter how I tried to set the Margin of the root element (its type does not matter) in MainWindow's ControlTemplate, it was always 0 when starting the app. The answer (thx to ILSpy) is in WindowChrome implementation.
When WindowChrome is attached to a Window, it is applying the Chrome feature, and among others, it executes a method WindowChromWorker._FixupTemplateIssues, which simple resets the window first visual element's Margin to a new Thickness instance, thus, erasing your custom settings by styles, templates, etc.
Workarounds can be:
Embedd your template into a new, look-less root element e.g. a Grid, so your original root's Margin won't be overridden
Adjust Padding of your root

Issue with applying style on WPF UserControl

I have a user-control and I want to use it in some other project. There is no problem when I set some value to its properties directly:
<local:MyUserControl prop1="val1" prop2="val2">
...
</local:MyUserControl>
But I can't apply a style to it. I tried:
<Window ...>
<Window.Resources>
<Style x:Key="MyUserControlStyle" TargetType="{x:Type local:MyUserControl}">
<Setter Property="prop1" Value="val1"/>
<Setter Property="prop2" Value="val2"/>
</Style>
</Window.Resources>
<Grid>
<local:MyUserControl Style="{StaticResource ResourceKey=MyUserControlStyle}">
...
</local:MyUserControl>
</Grid>
</Window>
Where did I wrong? -Thanks
Using dear #Mario Vernari's instructions, I found it out that the problem was due to a bad strategy which I'd used to create my UserControl. I wanted to create a UserControl that be able to hold some other ones. So I had tried this:
<UserControl x:Class="MyNamespace.MyUserControl"
...
Style="{DynamicResource ResourceKey=MyUserControlStyle}">
<UserControl.Resources>
...
<Style x:Key="MyUserControlStyle" TargetType="{x:Type UserControl}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type UserControl}">
<Border BorderBrush="{Binding Path=DP1}">
...
<ContentPresenter ... Content="{TemplateBinding Content}"/>
...
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</UserControl.Resources>
</UserControl>
Where DP1 is a dependency property of type Brush. The UserControl which has been created through this way works if you set its properties (like DP1) directly. Absolutely this is not the true way as #Mario told me:
...When you use an UserControl, it means that you already know its layout, and there is no need to style the control further. You are defining its style twice at the same time thus results a collision...
And he added:
Instead, you should use a CustomControl; Define the default style in the Themes folder (if you own regular Visual Studio, it makes automatically). Afterward, you may override the default style in your own app. In the same way you would do for a normal base class and its derived.
Follow this:
http://www.codeproject.com/KB/WPF/WPFCustomControl.aspx ...
Obviously, in this case we need to derive our lookless control from ContentControl class (instead of Control class). You may take a look at this & this to master the details.
Here, I give thanks to #Mario again. ;)
You are giving Style="{StaticResource ResourceKey=MyUserControlStyle}".
It's just - Style="{StaticResource MyUserControlStyle}".

Categories

Resources