I have a WPF button like so:
<Page.Resources>
<ImageBrush x:Key="black_pane_normal" ImageSource="/Images/TroubleShooting/black_pane_clear.png" />
</Page.Resources>
<Button x:Name="ButtonBlackPane" Background="{StaticResource black_pane_normal}" HorizontalAlignment="Left" VerticalAlignment="Top" Width="157" Height="136" MouseEnter="ButtonBlackPane_MouseEnter" MouseLeave="ButtonBlackPane_MouseLeave" Click="ButtonBlackPane_Click" RenderTransformOrigin="0.533,0.281" Margin="189,199,0,0"/>
My C# code behind is:
BitmapSource _black_pane_yellow_border = Imaging.CreateBitmapSourceFromHBitmap(InstallerToolkit.Properties.Resources.black_pane_yellow.GetHbitmap(),
IntPtr.Zero,
Int32Rect.Empty,
BitmapSizeOptions.FromEmptyOptions());
BitmapSource _black_pane_no_border = Imaging.CreateBitmapSourceFromHBitmap(InstallerToolkit.Properties.Resources.black_pane_clear.GetHbitmap(),
IntPtr.Zero,
Int32Rect.Empty,
BitmapSizeOptions.FromEmptyOptions());
private void ButtonBlackPane_MouseEnter(object sender, MouseEventArgs e)
{
ButtonBlackPane.Background = new ImageBrush(_black_pane_yellow_border);
}
private void ButtonBlackPane_MouseLeave(object sender, MouseEventArgs e)
{
ButtonBlackPane.Background = new ImageBrush(_black_pane_no_border);
}
My first problem is that my image does not fill the whole button background, how do I get this to fill it?
My second problem is that when the mouse enters the button, the correct background image gets displayed for a moment and then the default gray button image shows and my image goes away, how can I solve this?
First, it's not a good practice to set first the background with a static resource and then use code to set it each time to a new ImageBrush object. Have a look at the FindResource method (http://msdn.microsoft.com/de-de/library/system.windows.frameworkelement.findresource(v=vs.110).aspx) to use your resources in code behind.
Second, you should use Styles and Triggers to modify the appearance of a control depending for example on the MouseOver-State. There is a property called IsMouseOver which you can use for that. Here is an example:
<Page.Resources>
<Style TargetType="Button" x:Key="myButtonStyle">
<Setter Property="Foreground" Value="Red" />
<Setter Property="FontSize" Value="12" />
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="true">
<Setter Property="Foreground" Value="Blue" />
<Setter Property="Cursor" Value="Hand"/>
<Setter Property="FontSize" Value="16" />
</Trigger>
</Style.Triggers>
</Style>
</Page.Resources>
<Button Width="200" Height="100" Style="{StaticResource myButtonStyle}">Hello, World!</Button>
Third, because of the default template of a WPF button, you cannot change directly the background of it when hovering with the mouse. This problem is discussed and solved here: How do you change Background for a Button MouseOver in WPF?
If you want to have more Information about styling WPF controls and how to use the default templates, have a look here: http://msdn.microsoft.com/en-us/library/aa970773.aspx
Related
Trying to learn a fair bit about s and I got stuck on a particular subject. I want my buttons edited in size and alignment using a pre made style I have. An example:
<Button Style="{StaticResource ButtonFormat}">
</Button>
The button has a style saved in App.Xaml the style is written like this:
<Application.Resources>
<Style TargetType="Button" x:Key="ButtonFormat">
<Setter Property="Background" Value="#FF6E1400" />
<Setter Property="Margin" Value="5,5,5,5" />
</Style>
<Application.Resources>
Now, here is my dilemma:
I want to load another style that overwrites "ButtomFormat". I have been trying to experiment in VisualStatemanager to try and come up with the proper way of doing this but can't really find anything that explains enough for me on how to do it.
So in the visualstate such as below:
<VisualState x:Name="BigView" >
<VisualState.StateTriggers>
<AdaptiveTrigger MinWindowWidth="550" />
</VisualState.StateTriggers>
<VisualState.Setters>
<!--stuff goes here-->
<!--stuff goes here-->
</VisualState.Setters>
</VisualState>
I want to ooverwrite ButtonFormat with ButtonFormatBlue as such:
<Style TargetType="Button" x:Key="ButtonFormatBlue ">
<Setter Property="Background" Value="Blue" />
<Setter Property="Margin" Value="5,5,5,5" />
</Style>
I saw someone suggesting using C# instead of visualstatemanagers but I didn't properly understand that description, is it possible to load it from the visualstatetrigger as I want or am I looking at the wrong direction?
All aids are appreciated, thank you in advance!
You cannot override a resource, but you can change the Button's style property.
You first have to give the button a name:
<Button x:Name="MyButton" Style="{StaticResource ButtonFormat}">
</Button>
And now you can use the VisualStateManager to change the Style property:
<VisualState x:Name="BigView">
<VisualState.StateTriggers>
<AdaptiveTrigger MinWindowWidth="550" />
</VisualState.StateTriggers>
<VisualState.Setters>
<Setter Target="MyButton.Style"
Value="{StaticResource ButtonFormatBlue}" />
</VisualState.Setters>
</VisualState>
I saw someone suggesting using C# instead of visualstatemanagers but I didn't properly understand that description.
It means you can set a style to your Button manually in the code behind. For example, you can put your ButtonFormat and ButtonFormatBlue both in the App resource like this:
<Application.Resources>
<Style TargetType="Button" x:Key="ButtonFormat">
<Setter Property="Background" Value="#FF6E1400" />
<Setter Property="Margin" Value="5,5,5,5" />
</Style>
<Style TargetType="Button" x:Key="ButtonFormatBlue">
<Setter Property="Background" Value="Blue" />
<Setter Property="Margin" Value="5,5,5,5" />
</Style>
</Application.Resources>
Then your Button can be loaded with ButtonFormat style using StaticResource:
<Button x:Name="styleTestButton" Content="Style Sample" Style="{StaticResource ButtonFormat}"
VerticalAlignment="Bottom" Click="styleTestButton_Click" />
In the Button click event for example, you can change your Button's style as follows:
private void styleTestButton_Click(object sender, RoutedEventArgs e)
{
var ButtonFormatBlue = Application.Current.Resources.FirstOrDefault(r => r.Key.ToString() == "ButtonFormatBlue");
styleTestButton.Style = ButtonFormatBlue.Value as Style;
}
Or you can totally define a new style in the code behind and set this style to Button using C# in the code behind:
private void styleTestButton_Click(object sender, RoutedEventArgs e)
{
var dynamicStyle = new Style();
dynamicStyle.TargetType = typeof(Button);
dynamicStyle.Setters.Add(new Setter(BackgroundProperty, Colors.Blue));
dynamicStyle.Setters.Add(new Setter(MarginProperty, new Thickness(5, 5, 5, 5)));
styleTestButton.Style = dynamicStyle;
}
Need to know that as #MZetko said, we can't override a resource, this is why we created a new one.
is it possible to load it from the visualstatetrigger as I want or am I looking at the wrong direction?
Yes it's possible, but it's hard to tell whether you looked at the wrong direction, it depends on different scenarios. For example, if your UIElements are in the DataTemplate, then it doesn't work with StateTriggers, data binding is the best solution for this scenario. You can refer to the Remarks of VisualStateManager class, it shows perfect details of using VisualStateManager.
Hi all. I create an application with some (WPF) forms. I have a button on one form. I want to, at run time, copy this button onto a second form without having to create it again.
For example: I have 'X' button on form 1. At run time, I create a copy of this button on form 2 with all of the same property values as the original button on form 1.
The button:
<Button Content="Open Window" Click="ButtonClicked" Height="25"
HorizontalAlignment="Left" Margin="379,264,0,0" Name="button1"
VerticalAlignment="Top" Width="100" />
Any chance I can avoid having to reproduce this code?
You can define your own style for button in App.xaml:
<Application x:Class="WpfButton.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
StartupUri="MainWindow.xaml">
<Application.Resources>
<Style x:Key="myBtnStyle" TargetType="Button" >
<Setter Property="Content" Value="Open Window" />
<Setter Property="Height" Value="25" />
<Setter Property="Width" Value="100" />
<Setter Property="HorizontalAlignment" Value="Left" />
<Setter Property="Margin" Value="379,264,0,0" />
<Setter Property="VerticalAlignment" Value="Top" />
<EventSetter Event="Click" Handler="myBtn_Click" />
</Style>
</Application.Resources>
</Application>
Code behind:
public partial class App : Application
{
public void myBtn_Click(object sender, EventArgs e)
{
Button btn = sender as Button;
// ...
}
}
And when you want to assign created earlier style to the button, you should use StaticResource and name of your style:
<Button Style="{StaticResource myBtnStyle}" />
If you want to create an exact clone, then you will need to serialize the component and inject an ExpressionConverter into the serialization process. This will create a 'deep' clone. See here.
I am very new to Xaml but I have been taking advantage of the WPF for a while. For that reason I have made the below method which I use to change the image of a label or button anytime I wanna implement a mouse over or mouse leave event.
public void SImpleImageHadler(dynamic thing, String Path) {
ImageBrush IB = new ImageBrush();
IB.ImageSource = new BitmapImage(new Uri("pack://application:,,,/" + Path, UriKind.Absolute));
thing.Background = IB;
}
I would like to know how I can do this purely using xaml so that I wouldn't have to make a lot of event handlers for each of my UI elements.
In the style triggers for your button you can put this type of code to change properties. To see a image specific example check out this question.
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" Value="Blue" />
</Trigger>
</Style.Triggers>
And from this answer is an image example:
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background">
<Setter.Value>
<ImageBrush ImageSource="/MyProjectName;component/Images/MyImage.jpg" />
</Setter.Value>
</Setter>
</Trigger>
You should look into attached properties if you want to encapsulate such stuff for many different types of Buttons/Labels.
The final result should look like this:
<Button
ns2:MouseOverBackgroundChanger="YourURL"
/>
<Label
ns2:MouseOverBackgroundChanger="YourUrl2"
/>
This site has everything you need: http://msdn.microsoft.com/en-us/library/ms749011(v=vs.110).aspx (Attached Properties Overview)
How do I change an image on hover over in WPF behind code dynamically
i read an image from db and read also a hover image how to write code for image source and hover source?
You can utilise MouseEnter and MouseLeave events and change Image.Source in code behind but why not use Triggers to change Image.Source when IsMouseOver is true. Like that you won't have to handle state when mouse leaves your control as it will simply re evaluate your style and revert to previous image source.
Trigger example:
<ContentControl>
<ContentControl.Resources>
<BitmapImage UriSource="ad.png" x:Key="ImgBtnLightbulbOff"/>
<BitmapImage UriSource="ae.png" x:Key="ImgBtnLightbulbOn"/>
</ContentControl.Resources>
<ContentControl.Template>
<ControlTemplate TargetType="{x:Type ContentControl}">
<Image Source="{StaticResource ImgBtnLightbulbOff}" x:Name="PART_Image"/>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName="PART_Image" Property="Source" Value="{StaticResource ImgBtnLightbulbOn}"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</ContentControl.Template>
</ContentControl>
Image must wrapped in some other control as IsMouseOver trigger is not changing Source on Image alone. I use Resource images but they can be taken from any place, for example data bound.
But if you still need to do it in code behind here's an example:
XAML
<Image Source="{StaticResource ImgBtnLightbulbOff}"
MouseEnter="Image_MouseEnter"
MouseLeave="Image_MouseLeave"/>
Code:
private void Image_MouseLeave(object sender, MouseEventArgs e)
{
var img = sender as Image;
img.Source = (ImageSource)img.FindResource("ImgBtnLightbulbOff");
}
private void Image_MouseEnter(object sender, MouseEventArgs e)
{
var img = sender as Image;
img.Source = (ImageSource)img.FindResource("ImgBtnLightbulbOn");
}
I have developed a WPF Application with some buttons. Now i want to change the color of those buttons onmouseover,onmouseleave,onmouseenter by using triggers or any other events.
Any suggestion plz
Thanks in advance.
Inside the desired event, you can set the background color like this...
// Change the background color of button1 to Blue
button1.Background = Brushes.Blue;
You can also set this in a trigger:
<!-- Button will change from Blue to Yellow on MouseOver -->
<Style TargetType="{x:Type Button}">
<Setter Property="Background" Value="Blue" />
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" Value="Yellow" />
</Trigger>
</Style.Triggers>
</Style>
For even more details, check out the Property Triggers section of this article.