[英]Custom Button with a Viewbox inside
I have this style: 我有这种风格:
<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>
And I have two dependency properties. 而且我有两个依赖项属性。
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"));
}
I can set the Text
property without a problem, but somehow I can't set the Child of my Viewbox
. 我可以毫无问题地设置
Text
属性,但是以某种方式不能设置Viewbox
的Child。 The Viewbox
should receive a Canvas
as a Child
. Viewbox
应该会收到一个Canvas
作为Child
。
Calling this way, gives me an error: 以这种方式调用,给我一个错误:
<custom:ImageButton Text="New" Width="41" Child="{StaticResource NewIcon}"/>
Unable to cast object of 'System.Windows.TemplateBindingExpression' to type 'System.Windows.UIElement'. 无法转换“ System.Windows.TemplateBindingExpression”的对象来键入“ System.Windows.UIElement”。
As @Xaml-Lover said, you need this: 正如@ Xaml-Lover所说,您需要这样做:
<Viewbox x:Name="ViewBoxInternal">
<ContentPresenter ContentSource="{TemplateBinding Content}" Width="Auto" Height="Auto"/>
</Viewbox>
And you need to call like this: 您需要这样调用:
<custom:ImageButton Text="New" Content="{StaticResource NewIcon}" />
This is because, the Child property of Viewbox is not a Dependency Property. 这是因为Viewbox的Child属性不是依赖项属性。 A binding can only set to a Dependency property.
绑定只能设置为Dependency属性。 I would suggest you to follow a different approach.
我建议您采用其他方法。 Use ContentPresenter as a place holder for Child property and wrap it in aa Viewbox.
将ContentPresenter用作Child属性的占位符,并将其包装在Viewbox中。
<Viewbox x:Name="ViewBoxInternal">
<ContentPresenter ContentSource="Child"/>
</Viewbox>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.