Andrei Ilie Andrei Ilie - 1 year ago 157
C# Question

Changing content of button removes style WPF

Changing the content image of a button makes it ignore any previously defined layout properties.

What I suspect is the fact that upon changing

in the Button click event, it modifies:

Everything found between these tags.

And as my Style is inside those tags, it overrides it.

Here is the code for record:

private void ChangeImageFile(object sender, RoutedEventArgs e)
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "Image Files|*.png;*.jpeg;*.tiff;*.gif;*.bmp;*.jpg";
ofd.FilterIndex = 1;
ofd.Multiselect = false;
bool? ok = ofd.ShowDialog();
if(ok == true)
Image loaded = new Image();
loaded.Source = new BitmapImage(new Uri(ofd.FileName));
loaded.Height = 100;
this.Content = loaded;


<Button x:Name="BookCover" Click="ChangeImageFile">
<Image Source="Images/NewBook.png"/>
<Style TargetType="{x:Type Button}">
... LONG STYLE ...

Answer Source

When you're using this.Content, this refers to the current window and not to the button. You either need to access the button by Name or cast the sender.

By Name:

BookCover.Content = loaded;

Cast the sender:

Button btn = (sender as Button);
if(btn != null)
   btn.Content = loaded;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download