【发布时间】: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