内置Viewbox的自定义按钮

时间:2014-12-06 01:00:18

标签: c# wpf custom-controls

我有这种风格:

<Style TargetType="{x:Type local:ImageButton}" BasedOn="{StaticResource {x:Type Button}}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type local:ImageButton}">
                <Border>                 
                    <StackPanel Orientation="Horizontal">

                        <Viewbox x:Name="ViewBoxInternal" Child="{TemplateBinding Child}"/>
                        <TextBlock x:Name="TextBlockInternal" Text="{TemplateBinding Text}" />

                    </StackPanel>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

我有两个依赖属性。

static ImageButton()
{
    DefaultStyleKeyProperty.OverrideMetadata(typeof(ImageButton), new FrameworkPropertyMetadata(typeof(ImageButton)));

    ChildProperty = DependencyProperty.Register("Child", typeof(UIElement), typeof(ImageButton), new FrameworkPropertyMetadata());
    TextProperty = DependencyProperty.Register("Text", typeof(string), typeof(ImageButton), new FrameworkPropertyMetadata("Button"));
}

我可以毫无问题地设置Text属性,但不知怎的,我无法设置Viewbox的Child。 Viewbox应该会收到Canvas作为Child

这样打电话给我一个错误:

<custom:ImageButton Text="New" Width="41" Child="{StaticResource NewIcon}"/> 

无法转换&#39; System.Windows.TemplateBindingExpression&#39;的对象输入&#39; System.Windows.UIElement&#39;。

现在,工作......

正如@ Xaml-Lover所说,你需要这个:

<Viewbox x:Name="ViewBoxInternal">
    <ContentPresenter ContentSource="{TemplateBinding Content}" Width="Auto" Height="Auto"/>
</Viewbox>

你需要这样打电话:

<custom:ImageButton Text="New" Content="{StaticResource NewIcon}" />

VOÀLA

1 个答案:

答案 0 :(得分:1)

这是因为Viewbox的Child属性不是依赖属性。绑定只能设置为Dependency属性。我建议你采用不同的方法。使用ContentPresenter作为Child属性的占位符并将其包装在Viewbox中。

<Viewbox x:Name="ViewBoxInternal">
    <ContentPresenter ContentSource="Child"/>
</Viewbox>