简体   繁体   中英

Set style to textblock in code behind

How is it possible to set a style to a TextBlock in C# for a WinRT app?

textblock.Style = ???

What can I do here?

The "approved" answer didn't address the issue of how to do it in C# code-behind, which is what I thought the original post was asking.

To address that issue: For example, if you have a templated control based on Button, which is intended to display a SearchBox flyout, you could define the flyout within the button-initialization code like so:

        SearchBox searchBox = new SearchBox()
        {
            Style = Resources["SearchBoxCustomStyle"] as Style,
        };

Here, a custom resource was applied to the SearchBox.Style property. The above syntax assumes a resource reference in the control's XAML such as:

<Button.Resources>
    <ResourceDictionary Source="ms-appx:///Control_Assembly_Name/StandardStyles.xaml">
    </ResourceDictionary>
</Button.Resources>

In this case, the project containing the custom button control contains a StandardStyles.xaml that defines the resource "SearchBoxCustomStyle", as in:

<Style x:Key="SearchBoxCustomStyle" TargetType="SearchBox">
.
.
</Style>

In XAML/C#, you can set individual style properties on the element itself...

<TextBox Background="#FFEED908" FontSize="18" FontFamily="Stencil" x:Name="textBox"  Text="TextBox" />

If you edit the XAML directly in VS, you will get Intellisense that will let you discover the various properties. However, it is much easier to select the item and use the Properties dialog window to edit the properties in a visual manner.

If you want a reusable style, you must select the element and then select Format->Edit Style->Edit a Copy (or Create Empty...). You will then be in the style design mode and can update the style visually or directly in the XAML. You can then reuse that style on other elements like this:

<TextBox Style="{StaticResource MyStyle}" x:Name="textBox"   />

You would have to add your inline style (css) formatting. For example if you want your background to be black, height 20px and width 20px you would do:

textblock.style = "background-color: black; height: 20px; width: 20px;";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM