我有一个带有圆形图像的按钮的自定义类,因为我将在程序中多次使用它。我认为创建类,从Button继承并将我的设置拍入构造函数非常简单,但是当我运行程序时,按钮又大又普通(没有图像或文本)。这是我的课:
public class ImageButton : Button
{
public Button Button;
public ImageButton(string filename) : this(HorizontalAlignment.Center, VerticalAlignment.Center, filename)
{ }
public ImageButton(HorizontalAlignment hAlignment, VerticalAlignment vAlignment, string filename)
{
Button = new Button
{
Width = 35,
Height = 35,
Background = Brushes.Transparent,
HorizontalAlignment = hAlignment,
BorderBrush = Brushes.Transparent,
VerticalAlignment = vAlignment,
Content = new Image
{
Source = new BitmapImage(new Uri("pack://application:,,,/Resources/" + filename))
}
};
}
}
这是我对其中一个实例的实现
private void SetupHeaders(Grid resultGrid)
{
RowDefinition backbtn = new RowDefinition();
backbtn.Height = new GridLength(0.2, GridUnitType.Star);
resultGrid.RowDefinitions.Add(backbtn);
btn_Return = new ImageButton(HorizontalAlignment.Left, VerticalAlignment.Top, "returnicon.png");
Grid.SetRow(btn_Return, 0);
Grid.SetColumn(btn_Return, 0);
resultGrid.Children.Add(btn_Return);
}
btn_Return
在类的顶部简单定义
ImageButton btn_Return;
在构造函数中,使用属性初始化按钮,然后将其分配给属性。您实际上从未使用过初始化按钮。您一直在使用ImageButton,它仅是一个继承的按钮,因此您将获得默认行为。