Page 1 of 1

How to use styles in xamls for items created in code

Posted: 01 Mar 2020, 16:33
by Roest
I need some button rows depending on categories selected. So i have an ObservableCollection<Button> that gets updated and some xaml code
<ItemsControl ItemsSource="{Binding BuildButtons}" Grid.Row="1">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <StackPanel Orientation="Horizontal" />
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
</ItemsControl>
That works and I can see my buttons change depending on the collection. Now the button class has all kinds of setters for its attributes which all require c++ objects but how can I tell the buttons to use a style defined in a ResourceDictionary?

Re: How to use styles in xamls for items created in code

Posted: 02 Mar 2020, 20:37
by sfernandez
I think it would be better to create the buttons as part of a DataTemplate set on ItemsControl's ItemTemplate property:
<Grid.Resources>
  <DataTemplate x:Key="BuildButtonsItemTemplate">
    <Button Content="{Binding Name}" Command="{Binding Action}" Style="{StaticResource BuildButtonStyle}"/>
  </DataTemplate>
</Grid.Resources>
<ItemsControl ItemsSource="{Binding BuildButtons}" Grid.Row="1" ItemTemplate="{StaticResource BuildButtonsItemTemplate}">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <StackPanel Orientation="Horizontal" />
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
</ItemsControl>
But if you need for any reason to create the buttons in code, just get the style resource from the ResourceDictionary and set it in the button:
// assuming you are in the code-behind of a control in the UI tree, so you can call FindResource
Style* buttonStyle = FindResource<Style>("BuildButtonStyle");
Ptr<Button> buildButton = MakePtr<Button>();
buildButton->SetStyle(buttonStyle);