The contents of the settings button <Image> via styles

Cannot get this to work:

 <UserControl> <UserControl.Resources> <ResourceDictionary> <Style x:Key="TestStyle" TargetType="{x:Type Button}"> <Setter Property="Button.Content"> <Setter.Value> <Image Source="D:\Temp\dictionary16.png"/> </Setter.Value> </Setter> </Style> </ResourceDictionary> </UserControl.Resources> <StackPanel VerticalAlignment="Top" HorizontalAlignment="Left"> <Button Style="{StaticResource TestStyle}"/> <Button Style="{StaticResource TestStyle}"/> </StackPanel> </UserControl> 

This code throws the following exception (pointing to the second button):

The specified element is already a logical child of another element. Disable it first.

+6
source share
2 answers

The style creates one instance of Image ; you cannot use it in two places like this. You can create an image as a separate resource with x:Shared = false and refer to it in style, and then a new one will be created in each place where the style is used.


eg.

 <UserControl> <UserControl.Resources> <Image x:Key="img" x:Shared="false" Source="D:\Temp\dictionary16.png" /> <Style x:Key="TestStyle" TargetType="{x:Type Button}"> <Setter Property="Content" Value="{StaticResource img}" /> </Style> </UserControl.Resources> <StackPanel VerticalAlignment="Top" HorizontalAlignment="Left"> <Button Style="{StaticResource TestStyle}" /> <Button Style="{StaticResource TestStyle}" /> </StackPanel> </UserControl> 
+18
source

Yesterday I found a user with a similar problem: WPF - changing the contents of a button in style?

This post brought me to this soloution (couldn't post it due to an 8 hour stackoverflow -.- restriction)

 <Setter Property="ContentTemplate"> <Setter.Value> <DataTemplate> <Image Source="{mcWPF:LangRes imgSettings16, Bitmap}" Height="14"/> </DataTemplate> </Setter.Value> </Setter> 

I don't know that the weather is cleaner / dirtier / better than HB soloution

+11
source

Source: https://habr.com/ru/post/890595/


All Articles