在资源字典中:
<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 的宽度和高度将设置为自动并根据 >内容控制。但是,Style 无法再获得准确的高度和宽度。
我的问题是:
有没有办法让我的Style 正确显示包含在ContentControl 中的TextBox。由于 ContentControl 是可拖动的,我无法在 TextBox 内部设置精确的高度和宽度。
最佳答案
如果您没有显式设置 Width/Height
,则必须将模板绑定(bind)更改为 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。
关于c# - 如何将TemplateBinding应用到 "Auto"高宽,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13828500/