如何将TemplateBinding应用于“自动”高度和宽度

时间:2012-12-11 21:06:03

标签: c# wpf xaml textbox templatebinding

在资源词典中:

<Style x:Key="ControlFrame" TargetType="{x:Type TextBox}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type TextBox}">
                <Border Background="{TemplateBinding Background}" BorderThickness="2">
                    <ScrollViewer Margin="0" x:Name="PART_ContentHost" />
                    <Border.BorderBrush>
                        <VisualBrush>
                            <VisualBrush.Visual>
                                <Rectangle StrokeDashArray="8, 2" Stroke="{TemplateBinding BorderBrush}" 
                                           StrokeThickness="2"
                                           Width="{TemplateBinding Width}"
                                           Height="{TemplateBinding Height}"/>
                            </VisualBrush.Visual>
                        </VisualBrush>
                    </Border.BorderBrush>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

在C#中:

TextBox textbox = new TextBox();
textbox.Width = 200;
textbox.Height = 200;
Style style = this.FindResource("ControlFrame") as Style;
textbox.Style = style;
canvas.Children.Insert(0, textbox);

我可以正确地获得虚线边框。

enter image description here

如果我将文本框包装到 ContentControl 中,而不提供文本框的高度和宽度,如下所示:

TextBox textbox = new TextBox();
Style style = this.FindResource("ControlFrame") as Style;
textbox.Style = style;
ContentControl cc = new ContentControl();
cc.Content = textbox;
cc.Height = 200;
cc.Width = 200;
canvas.Children.Insert(0, cc);

结果错过了:

enter image description here

我猜原因是:

在Style中,我使用以下内容设置边框的宽度和高度。它们依赖于 TextBox 的宽度和高度。

Width="{TemplateBinding Width}"
Height="{TemplateBinding Height}"

如果我将 TextBox 包装到 ContentControl 中, TextBox 的宽度和高度设置为自动并根据 ContentControl中即可。但是,样式无法再获得精确的高度和宽度。

我的问题是:

有没有办法让我的样式正确显示 TextBox 包装在 ContentControl 中。由于 ContentControl 是可拖动的,我无法将精确的高度和宽度设置为内部 TextBox

1 个答案:

答案 0 :(得分:5)

如果您没有明确设置Width/Height,则必须将模板绑定更改为ActualWidth/ActualHeight

<VisualBrush.Visual>
   <Rectangle StrokeDashArray="8, 2" Stroke="{TemplateBinding BorderBrush}" 
              StrokeThickness="2"
              Width="{TemplateBinding ActualWidth}"
              Height="{TemplateBinding ActualHeight}"/>
</VisualBrush.Visual>

布局:(如果我理解你的问题)

 <Grid>
     <ContentControl >
        <TextBox BorderBrush="Red" Background="Blue" Style="{StaticResource ControlFrame}" />
     </ContentControl>
 </Grid>

ActualWidth/ActualHeight将返回控件的渲染大小,Width/Height将返回NaN,如果在其他位置没有明确设置的话。

相关问题