我在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中,按钮不会呈现。
答案 0 :(得分:3)
你在TemplateBinding
之后:
<TextBlock Grid.Row="0" TextAlignment="Center" Text="{TemplateBinding PrimaryText}" TextWrapping="Wrap" FontSize="14.667" />
<TextBlock Grid.Row="1" TextAlignment="Left" Text="{TemplateBinding SecondaryText}" FontSize="10.667" />
此绑定专门用于控件模板 - 它指的是控件中的依赖项属性。 (请注意,相反,常规绑定是指当前DataContext
中的属性。)
修改
要使其看起来像一个按钮,请复制default control template for Button
并将其ContentPresenter
替换为如下所示:
<ContentControl Margin="2"
HorizontalAlignment="Center"
VerticalAlignment="Center"
RecognizesAccessKey="True"
ContentTemplate="{TemplateBinding ContentTemplate}">
<ContentControl.Content>
<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>
</ContentControl.Content>
</ContentControl>