4

在资源字典中:

<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);

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

在此处输入图像描述

如果我将文本框包装到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);

结果错过了:

在此处输入图像描述

我猜原因是:

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

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

如果我将TextBox包装到ContentControl中,则TextBox的 Width 和 Height 设置为 Auto 并根据ContentControl进行更改。但是,样式无法再获得确切的高度和宽度。

我的问题是:

有什么方法可以让我的Style为包含在ContentControl中的TextBox正确显示。由于ContentControl是可拖动的,因此我无法将确切的 Height 和 Width 设置为内部TextBox

4

1 回答 1

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。

于 2012-12-11T21:28:33.227 回答