Joshua Lowry
Joshua Lowry

Reputation: 1105

XAML Data Template Style Border with TextBlock

I'm not sure if this is possible, but I want to see if anyone knows. I want to write a style for a data template that is a Border with a TextBlock inside. Ideally, I would like to have the whole thing in one style. Right now I have the style for the Border and the TextBlock separately.

Here is my DataTemplate:

<DataTemplate DataType="{x:Type local:MyObject}">
    <Border Style="{StaticResource BorderStyle}">
        <TextBlock Style="{StaticResource TextBlockStyle}"/>
    </Border>
</DataTemplate>

Style for the Border

<Style x:Key="BorderStyle" TargetType="Border">
    <Setter Property="BorderBrush" Value="Black"/>
    <Setter Property="BorderThickness" Value="1"/>
    <Setter Property="CornerRadius" Value="90"/>
    <Setter Property="Width" Value="45"/>
    <Setter Property="Height" Value="45"/>
    <Setter Property="Background" Value="White"/>
    <Setter Property="Opacity" Value=".75"/>
</Style>

Style for the TextBlock

<Style x:Key="TextBlockStyle" TargetType="TextBlock">
    <Setter Property="Text" Value="{Binding Name}"/>
    <Setter Property="VerticalAlignment" Value="Center"/>
    <Setter Property="HorizontalAlignment" Value="Center"/>
</Style>

Code Complete gave me additional properties for the Border which I thought would work, but they didn't seem to work.

<Style x:Key="BorderStyle" TargetType="Border">
    ...
    <Setter Property="TextBlock.VerticalAlignment" Value="Center"/>
    ...
</Style>

Upvotes: 2

Views: 5598

Answers (1)

Sagar
Sagar

Reputation: 464

You can create a single DataTemplate and use it as a static resource in your application. I have achieved it in the following mentioned way.

<Window.Resources>
    <DataTemplate x:Key="borderedTemplate">
        <Border BorderBrush="Black" BorderThickness="1" CornerRadius="90" Width="45" Height="45" Background="White" Opacity=".75">
            <TextBlock VerticalAlignment="Center" HorizontalAlignment="Center" Text="{Binding Name}">
            </TextBlock>
        </Border>
    </DataTemplate>
</Window.Resources>

After defining this template, we can use this template using borderedTemplate key. This particular template, it generates a nice circular border around a TextBlock.

Upvotes: 2

Related Questions