繁体   English   中英

带有视图框的自定义按钮

[英]Custom Button with a Viewbox inside

我有这种风格:

<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}"/> 

无法转换“ System.Windows.TemplateBindingExpression”的对象来键入“ System.Windows.UIElement”。

工作中...

正如@ Xaml-Lover所说,您需要这样做:

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

您需要这样调用:

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

VOÀLA

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM