我在 XAML 中有一个按钮,我按照我需要的方式设置了它的样式。这是该按钮的 XAML 代码:
<Button x:Name="btnAddNewItem"
Grid.Column="0" Grid.Row="0"
FontSize="15"
BorderThickness="1.5"
HorizontalContentAlignment="Center"
VerticalContentAlignment="Center"
Foreground="White"
Background="White"
BorderBrush="#0091EA" Margin="5,0,0,0" Height="90" Width="90">
<Button.Template>
<ControlTemplate TargetType="{x:Type Button}">
<Border BorderThickness="{TemplateBinding BorderThickness}"
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}">
<ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
VerticalAlignment="{TemplateBinding VerticalContentAlignment}" />
</Border>
</ControlTemplate>
</Button.Template>
我想实现这样的目标,所以我想删除 xaml 按钮,并在需要时以编程方式创建相同的按钮,具有相同的样式和我在 xaml 中所做的一切,例如我想如何创建它:
private void AddSubmenuButton(string name)
{
MyButton button = new MyButton();
button.ButtonText = name;
}
这可能吗?如果可以:如何?
PS我尝试了经典的方式,像这样:
Button a = new Button();
a.BorderThickness = new Thickness(1);
a.Foreground = new SolidColorBrush(Colors.Black);
a.BorderBrush = mySolidColorBrush;
a.Content = "Button1";
a.Width = 90;
a.Height = 90;
但我明白了:
可能会注意到它的厚度根本不是 1,它有一些奇怪的值,我不知道如何更改它。所以这就是为什么我在 xaml 中创建了看起来更漂亮的按钮并且我想调用它的原因/从后面的代码创建它。
编辑:
@mm8 非常感谢!而已!
这是很棒的伙伴,但是如果我想在我的按钮中放置图标 + 文本,我通常会添加这样的东西,这对我来说很好:
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="80*">
<RowDefinition Height="20*"/>
</Grid.RowDefinitions>
<Image Source="/MyProject.Wpf;component/Icons/customer-icon.png" Margin="10" Grid.Row="0" Width="Auto"/>
<TextBlock Foreground="Black" Margin="0,0,0,3" Grid.Row="1" VerticalAlignment="Center" HorizontalAlignment="Center" >Izlaz</TextBlock>
</Grid>
如您所见,我会将 Grid 添加到我的按钮中,它看起来像这样:
<Button x:Name="btnAddNewItem"
Grid.Column="0" Grid.Row="0"
FontSize="15"
ToolTip="Podaci"
BorderThickness="1.5"
HorizontalContentAlignment="Center"
VerticalContentAlignment="Center"
Foreground="White"
Background="White"
BorderBrush="#0091EA" Margin="5,0,0,0" Height="90" Width="90">
<Button.Template>
<ControlTemplate TargetType="{x:Type Button}">
<Border BorderThickness="{TemplateBinding BorderThickness}"
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}">
<ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
VerticalAlignment="{TemplateBinding VerticalContentAlignment}" />
</Border>
</ControlTemplate>
</Button.Template>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="80*">
<RowDefinition Height="20*"/>
</Grid.RowDefinitions>
<Image Source="/MyProject.Wpf;component/Icons/customer-icon.png" Margin="10" Grid.Row="0" Width="Auto"/>
<TextBlock Foreground="Black" Margin="0,0,0,3" Grid.Row="1" VerticalAlignment="Center" HorizontalAlignment="Center" >Izlaz</TextBlock>
</Grid>
</Button>
那么我能否以某种方式实现这一点(我的按钮中的图像+文本)也可以以编程方式创建它。