4

リソース辞書:

<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}"

TextBoxContentControlにラップすると、TextBoxのWidthとHeightがAutoに設定され、 ContentControlに従って変更されます。ただし、スタイルは正確な高さと幅を取得できなくなります。

私の質問は:

ContentControl内にラップされたTextBoxに対してスタイルを正しく表示する方法はありますか?ContentControlはドラッグ可能であるため、 TextBoxの内側に正確な高さと幅を設定できません。

4

1 に答える 1

5

を明示的に設定していない場合は、テンプレートのバインディングを次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を返します。

于 2012-12-11T21:28:33.227 に答える