更改按钮的内容会删除样式WPF

时间:2016-08-31 05:41:04

标签: c# wpf

更改按钮的内容图像使其忽略任何先前定义的布局属性。

我怀疑的是,在按钮点击事件中更改this.Content后,它会修改:

<Button>
     Everything found between these tags.
</Button>

由于我的Style位于这些标签内,它会覆盖它。

以下是记录的代码:

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">
            <Button.Content>
                <Image Source="Images/NewBook.png"/>
            </Button.Content>
            <Button.Style>
                <Style TargetType="{x:Type Button}">
                    ... LONG STYLE ...
                </Style>
            </Button.Style>
        </Button>

1 个答案:

答案 0 :(得分:1)

当您使用this.Content时,这指的是当前窗口而不是按钮。您需要按名称访问按钮或投射发件人。

按姓名:

BookCover.Content = loaded;

投放发件人:

Button btn = (sender as Button);
if(btn != null)
   btn.Content = loaded;