Reputation: 3262
I'm creating buttons dynamically that have images as their background, The problem is the default WPF button animation on mouse over deform my button and hide the image.
Is there any way I can make my own button style for these buttons without creating a custom button class, and using something like myButtton.property = something;
in C# code not XAML because I'm creating the button dynamically.
Upvotes: 0
Views: 1034
Reputation: 3496
YOu can do this by creating a template for button in resources...
Here is a sample...
XAML Code...
<UserControl.Resources>
<ControlTemplate x:Key="buttonTemplate">
<Image Name="btnImage" Source="C:\Users\Public\Pictures\Sample Pictures\Desert.jpg"></Image>
</ControlTemplate>
</UserControl.Resources>
<Grid Name="layoutRoot">
</Grid>
</UserControl>
in code behind:
Button button = new Button();
ControlTemplate ct = this.Resources["buttonTemplate"] as ControlTemplate;
Image img = ct.LoadContent() as Image;
img.Source = new BitmapImage(new Uri(@"C:\Users\Public\Pictures\Sample Pictures\Desert.jpg",UriKind.RelativeOrAbsolute));
button.Template = ct;
button.Height = 200;
button.Width = 200;
layoutRoot.Children.Add(button);
if you are adding buttons from view model you can get the button template from app resources (by putting the resource in app.xaml file)
Upvotes: 2
Reputation: 2257
You could set the ControlTemplate of the button. Since you do not wish to do this in the XAML here is one way you could do it in the code-behind:
string buttonTemplate =
"<ControlTemplate TargetType=\"Button\">" +
"<Image Source=\"myImage.gif\" />" +
"</ControlTemplate>";
myButton.Template = (ControlTemplate)XamlReader.Parse(template);
This is just for a basic button with an Image as the content. If you want to have custom animations on actions such as mouseover you can add XAML to the code-behind string using the VisualStateManager to take care of that.VisualStateManager
Upvotes: 0