我在 WPF 中有应用程序,我需要在其中创建许多具有相同内容布局的按钮。它当前在 Window 中定义为:
<Button Grid.Row="0" Grid.Column="0" Margin="4" >
<Button.Content>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="0.85*" />
<RowDefinition Height="0.25*" />
</Grid.RowDefinitions>
<TextBlock Grid.Row="0" TextAlignment="Center" Text="Primary Text that can wrap" TextWrapping="Wrap" FontSize="14.667" />
<TextBlock Grid.Row="1" TextAlignment="Left" Text="smaller text" FontSize="10.667" />
</Grid>
</Button.Content>
</Button>
我最理想的做法是将其更改为:
<controls:MultiTextButton Grid.Row="0" Grid.Column="0" PrimaryText="Primary Text that can wrap" SecondaryText="smaller text" />
对或错我创建了以下类:
public class MultiTextButton : Button
{
public static readonly DependencyProperty PrimaryTextProperty = DependencyProperty.Register("PrimaryText", typeof(String), typeof(MultiTextButton));
public static readonly DependencyProperty SecondaryTextProperty = DependencyProperty.Register("SecondaryText", typeof(String), typeof(MultiTextButton));
static MultiTextButton()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(MultiTextButton), new FrameworkPropertyMetadata(typeof(MultiTextButton)));
}
public string PrimaryText
{
get { return (string)GetValue(PrimaryTextProperty); }
set { SetValue(PrimaryTextProperty, value); }
}
public string SecondaryText
{
get { return (string)GetValue(SecondaryTextProperty); }
set { SetValue(SecondaryTextProperty, value); }
}
}
我现在不确定如何设置“模板”以在窗口中以原始代码的格式显示内容。我试过了:
<ControlTemplate x:Key="MultiTextButtonTemplate" TargetType="{x:Type controls:MultiTextButton}">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="0.85*" />
<RowDefinition Height="0.25*" />
</Grid.RowDefinitions>
<TextBlock Grid.Row="0" TextAlignment="Center" Text="{Binding PrimaryText}" TextWrapping="Wrap" FontSize="14.667" />
<TextBlock Grid.Row="1" TextAlignment="Left" Text="{Binding SecondaryText}" FontSize="10.667" />
</Grid>
</ControlTemplate>
但在 Blend 和 Visual Studio 中,该按钮未呈现。