【问题标题】:How to apply TemplateBinding to "Auto" height and width如何将 TemplateBinding 应用于“自动”高度和宽度
【发布时间】:2012-12-11 21:06:03
【问题描述】:

在资源字典中:

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

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

如果我将 Textbox 包装到 ContentControl 中而不给出 Textbox 的高度和宽度,如下所示:

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 并根据 >内容控制。但是,Style 无法再获得确切的高度和宽度。

我的问题是:

有什么方法可以让我的 Style 正确显示在 ContentControl 中包裹的 TextBox。由于 ContentControl 是可拖动的,因此我无法在 TextBox 内部设置精确的高度和宽度。

【问题讨论】:

    标签: c# wpf xaml textbox templatebinding


    【解决方案1】:

    如果您没有明确设置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,如果它没有在别处明确设置。

    【讨论】:

      猜你喜欢
      • 2017-11-29
      • 1970-01-01
      • 1970-01-01
      • 2020-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-05
      • 2013-04-06
      相关资源
      最近更新 更多