Roest
Topic Author
Posts: 26
Joined: 15 Jan 2020, 15:30

How to use styles in xamls for items created in code

01 Mar 2020, 16:33

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?
 
User avatar
sfernandez
Site Admin
Posts: 1911
Joined: 22 Dec 2011, 19:20

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

02 Mar 2020, 20:37

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);

Who is online

Users browsing this forum: No registered users and 1 guest