don*_*ngx 4 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>
Run Code Online (Sandbox Code Playgroud)
在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);
Run Code Online (Sandbox Code Playgroud)
我可以正确地获得虚线边框.

如果我包裹文本框成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);
Run Code Online (Sandbox Code Playgroud)
结果错过了:

我想原因是:
在Style中,我使用以下内容设置边框的宽度和高度.它们依赖于TextBox的宽度和高度.
Width="{TemplateBinding Width}"
Height="{TemplateBinding Height}"
Run Code Online (Sandbox Code Playgroud)
如果我将TextBox包装到ContentControl中,TextBox的Width和Height将设置为Auto并根据ContentControl进行更改.但是,Style无法再获得精确的高度和宽度.
我的问题是:
有没有什么办法让我的风格正常显示的文本框一内包裹ContentControl中.由于ContentControl是可拖动的,我无法将精确的高度和宽度设置为内部TextBox.
如果您没有明确设置Width/Height,则必须将模板绑定更改为ActualWidth/ActualHeight:
<VisualBrush.Visual>
<Rectangle StrokeDashArray="8, 2" Stroke="{TemplateBinding BorderBrush}"
StrokeThickness="2"
Width="{TemplateBinding ActualWidth}"
Height="{TemplateBinding ActualHeight}"/>
</VisualBrush.Visual>
Run Code Online (Sandbox Code Playgroud)
布局:(如果我理解你的问题)
<Grid>
<ContentControl >
<TextBox BorderBrush="Red" Background="Blue" Style="{StaticResource ControlFrame}" />
</ContentControl>
</Grid>
Run Code Online (Sandbox Code Playgroud)
ActualWidth/ActualHeight将返回控件的渲染大小,Width/Height如果其他地方没有明确设置,将返回NaN.
| 归档时间: |
|
| 查看次数: |
2339 次 |
| 最近记录: |