Reputation: 1065
The following code will create tow buttons but the style will only be applied to the second I know I can use a template instead but I was wondering why this setup does not work?
<Window x:Class="WpfApplication9.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<Style TargetType="Button">
<Setter Property="Content">
<Setter.Value>
<Grid>
<TextBlock Text="help"></TextBlock>
</Grid>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition></RowDefinition>
<RowDefinition></RowDefinition>
<RowDefinition></RowDefinition>
<RowDefinition></RowDefinition>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition></ColumnDefinition>
<ColumnDefinition></ColumnDefinition>
<ColumnDefinition></ColumnDefinition>
</Grid.ColumnDefinitions>
<Button Grid.Row="1" Grid.Column="0"></Button>
<Button Grid.Row="1" Grid.Column="1"></Button>
</Grid>
Upvotes: 0
Views: 57
Reputation: 25623
You cannot (or at least should not) use a UI element in a Setter
, because a UI element can only exist in one place in a visual tree. That is to say: a UI element may only have one parent element. Try setting the content to some non-UI value, like a simple string, and let WPF apply a data template for you:
<Setter Property="Content" Value="help" />
If you want to specify complex UI content, set a ContentTemplate
instead; that will allow you to use a DataTemplate
to build up a common visual tree.
Note, however, that it is unusual to set Content
on a button setter; the content typically varies from button to button, whereas styles are meant to set property values that should be common across control instances.
Upvotes: 4
Reputation: 33384
Style
is shared so there is only one instance of Grid
and since Visual
can have only one parent it will be visible in the last place where you use it. You can disable sharing for Style
<Style ... x:Shared="False">
When set to false, modifies WPF resource-retrieval behavior so that requests for the attributed resource create a new instance for each request instead of sharing the same instance for all requests.
Upvotes: 3