How to use styles in xamls for items created in code
I need some button rows depending on categories selected. So i have an ObservableCollection<Button> that gets updated and some xaml code
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?
Code: Select all
<ItemsControl ItemsSource="{Binding BuildButtons}" Grid.Row="1">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
-
-
sfernandez
Site Admin
- Posts: 2062
- Joined:
Re: How to use styles in xamls for items created in code
I think it would be better to create the buttons as part of a DataTemplate set on ItemsControl's ItemTemplate property:
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:
Code: Select all
<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>
Code: Select all
// 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