Topic Author
Posts: 35
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">
            <StackPanel Orientation="Horizontal" />
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
Site Admin
Posts: 2062
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:
  <DataTemplate x:Key="BuildButtonsItemTemplate">
    <Button Content="{Binding Name}" Command="{Binding Action}" Style="{StaticResource BuildButtonStyle}"/>
<ItemsControl ItemsSource="{Binding BuildButtons}" Grid.Row="1" ItemTemplate="{StaticResource BuildButtonsItemTemplate}">
            <StackPanel Orientation="Horizontal" />
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>();

Who is online

Users browsing this forum: No registered users and 1 guest