リソース辞書:
<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に従って変更されます。ただし、スタイルは正確な高さと幅を取得できなくなります。
私の質問は:
ContentControl内にラップされたTextBoxに対してスタイルを正しく表示する方法はありますか?ContentControlはドラッグ可能であるため、 TextBoxの内側に正確な高さと幅を設定できません。