2

How do you set the .Template property of an element (e.g. a FlipViewItem in my case) using C# code to a predefined one in my StandardStyles.xaml

This is the template if it's relevant:

<ControlTemplate x:Key="DocumentFlipViewItemControlTemplate" TargetType="FlipViewItem">
    <Grid Width="160" HorizontalAlignment="Left">
        <MyProject:DocumentTabControl Name="MainDocumentTabControl"/>
    </Grid>
</ControlTemplate>

Please note this is a different question from How to set Control Template in code? - that question creates a template on the fly and then assigns it to the control, I just want to set a predefined template.

Community
  • 1
  • 1
James
  • 30,496
  • 19
  • 86
  • 113

3 Answers3

3
    <Style x:Key="DocumentFlipViewItemStyle" TargetType="FlipViewItem" >
            <Setter Property="Template" Value="{StaticResource DocumentFlipViewItemControlTemplate}"/>
    </Style>
user1064519
  • 2,180
  • 12
  • 13
  • Could a style be used for the a specific `FlipView` to cause all it's `FlipViewItem`s to have the same template? – James Dec 31 '12 at 16:45
  • 1
    I am not familiar with this control, but if it has ItemContainerStyle property, you should set it: ItemContainerStyle="{StaticResource DocumentFlipViewItemStyle}" – user1064519 Dec 31 '12 at 16:49
0

Change this part:

TargetType="FlipViewItem"

to something like this:

TargetType="{x:Type FlipViewItem}"

And that will apply the style to that type across the application. Now one thing to note is that you may need the namespace declaration in front of your type. So, if it's coming from something other than the standard libraries you may need something like:

TargetType="{x:Type local:FlipViewItem}"
Mike Perrenoud
  • 66,820
  • 29
  • 157
  • 232
  • Okay, that's pretty close, however I have other `FlipViewItem`s that I don't want to use this template, is there a way to set the template for a specific instance of a `FlipViewItem`? – James Dec 31 '12 at 16:39
0

I know this question is old, but you can simply assign it like this:

var template = 
    (ControlTemplate)Application.Current
        .MainWindow // Your WPF window.
        .FindResource("DocumentFlipViewItemControlTemplate");

and then you assign it to your FlipViewItem like this:

var flipItem = new FlipViewItem { Template = template };
Jakub Loksa
  • 537
  • 1
  • 14
  • 32