【问题标题】:How to set size of CustomControl in Silverlight using TemplateBinding?如何使用 TemplateBinding 在 Silverlight 中设置 CustomControl 的大小?
【发布时间】:2013-02-19 09:00:10
【问题描述】:

我正在开发一个 Silverlight CustomControl,它定义了一个名为 SpinnerSize 的依赖属性。现在我想使用TemplateBinding 将默认模板内Border 的宽度和高度设置为SpinnerSize-property:

<Style TargetType="local:MyCustomControl">
    <Setter Property="SpinnerSize" Value="12" />
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="local:MyCustomControl">
                <Border 
                    Width="{TemplateBinding SpinnerSize}"
                    Height="{TemplateBinding SpinnerSize}"
                    Background="Red" />
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

上例中的SpinnerSize引用定义如下:

public static readonly DependencyProperty SpinnerSizeProperty = 
    DependencyProperty.Register(
        "SpinnerSize", 
        typeof(int), 
        typeof(MyCustomControl),
        new PropertyMetadata(default(int)));

public int SpinnerSize
{
    get { return (int)this.GetValue(SpinnerSizeProperty); }
    set { this.SetValue(SpinnerSizeProperty, value); }
}

结果是根本看不到边框。如果我手动将边框的宽度和高度设置为一个值,一切正常。

TemplateBinding 是实现这一目标的有效方法,还是我必须在控件中的 OnApplyTemplate() 方法中手动设置宽度和高度?

【问题讨论】:

    标签: silverlight xaml custom-controls templatebinding


    【解决方案1】:

    你的 XAML 看起来不错,像这样使用 TemplateBinding 是有效的,所以问题一定出在你的 DependencyProperty 上。

    高度和宽度是双精度值。 Binding 引擎不处理隐式强制转换。

    将您的 DP 更改为该类型,它应该可以正常工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多