Monospace Margin between elements in WPF - wpf

I want the space between the child elements in, for example, StackPanel be the same. When using the same Margin for child elements, gap between neighbors doubles. I'm using a little trick to solve this, but it seems to me there is more elegant solution. May be you have one?
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Style x:Key="MyButtonStyle" TargetType="Button">
<Setter Property="Margin" Value="4,4,0,4" />
...
</Style>
<Style x:Key="LastMyButtonStyle" TargetType="Button" BasedOn="{StaticResource MyButton}">
<Setter Property="Margin" Value="4" />
</Style>
I'm using MyButtonStyle for all buttons except the last one, which use LastMyButtonStyle.

Put the StackPanel in another container, i.e. a Border, and set its Margin to the same value as those of the Buttons:
<Border>
<StackPanel Orientation="Horizontal" Margin="2">
<Button Margin="2" Content="Button 1"/>
<Button Margin="2" Content="Button 2"/>
<Button Margin="2" Content="Button 3"/>
</StackPanel>
</Border>

Related

Override or add some style properties in WPF

I am porting a Bootstrap theme to WPF and faced a problem: I can't change some properties using additional style for StackPanel. I have ResourceDictionary containing BtnBase base style and BtnPrimary, BtnSecondary etc. All of them were inherited from BtnBase and contain only color properties. BtnBase does not contain any margin rule. When I try to add margin rule for a current StackPanel, there is no effect. I read about styles and knew that more than one style can't be applied, styles in ResourceDictionary have higher priority and I should use BasedOn. But I need to copy and paste my style in the StackPanel and replace BasedOn for each button variant. Is there a way to bypass it and add margin property for all styles?
code:
<StackPanel Orientation="Horizontal" Height="32">
<StackPanel.Resources>
<Style TargetType="{x:Type Button}" BasedOn="{StaticResource BtnBase}>
<Setter Property="Margin" Value="0,0,10,0"/>
</Style>
</StackPanel.Resources>
<Button Style="{DynamicResource BtnPrimary}" Content="Primary" />
<Button Style="{DynamicResource BtnSecondary}" Content="Secondary" />
<Button Style="{DynamicResource BtnSuccess}" Content="Success" />
<Button Style="{DynamicResource BtnInfo}" Content="Info" />
<Button Style="{DynamicResource BtnWarning}" Content="Warning" />
<Button Style="{DynamicResource BtnDanger}" Content="Danger" />
<Button Style="{DynamicResource BtnLight}" Content="Light" />
<Button Style="{DynamicResource BtnDark}" Content="Dark" />
</StackPanel>
You can treat all buttons as Items in ListBox.
ListBox will create a ListBoxItem for each Button, and you can add Margin to those ListBoxItems, using ItemContainerStyle. That doesn't modify Buttons styles, but creates same effect.
In ItemContainerStyle I also change ListBoxItem template to undo hover, selection colors, etc, which can change appearance - just plain ContentPresenter is left.
ItemsPanel by default is vertical StackPanel, but I changed ItemsPanel and layout to horizontal StackPanel.
<ListBox>
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal" Height="32"/>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="Margin" Value="4"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListBoxItem">
<ContentPresenter/>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ListBox.ItemContainerStyle>
<Button Style="{DynamicResource BtnPrimary}" Content="Primary" />
<Button Style="{DynamicResource BtnSecondary}" Content="Secondary" />
<Button Style="{DynamicResource BtnSuccess}" Content="Success" />
<Button Style="{DynamicResource BtnInfo}" Content="Info" />
<Button Style="{DynamicResource BtnWarning}" Content="Warning" />
<Button Style="{DynamicResource BtnDanger}" Content="Danger" />
<Button Style="{DynamicResource BtnLight}" Content="Light" />
<Button Style="{DynamicResource BtnDark}" Content="Dark" />
</ListBox>

Add name to specific style control wpf

I have a custom contextmenu:
<Window.Resources>
<ContextMenu x:Key="RowMenu" DataContext="{Binding PlacementTarget.DataContext, RelativeSource={RelativeSource Self}}">
<ContextMenu.Style>
<Style TargetType="ContextMenu">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate>
<Grid Background="Transparent">
<Border Background="#1c1c1c" Height="70" Width="170" CornerRadius="10">
<StackPanel Orientation="Vertical">
<Button x:Name="openinBrowser" Click="Button_Click_1">
<Grid Width="170">
<materialDesign:PackIcon Kind="OpenInApp" VerticalAlignment="Center" Foreground="{StaticResource PrimaryHueMidBrush}" HorizontalAlignment="Left"/>
<Label FontFamily="Champagne & Limousines" Content="Action 1" FontSize="7" HorizontalAlignment="Center" Foreground="LightGray" VerticalAlignment="Center"/>
</Grid>
<Button.Style>
<Style BasedOn="{StaticResource MaterialDesignRaisedAccentButton}" TargetType="Button">
<Setter Property="Background" Value="Transparent"/>
<Setter Property="BorderBrush" Value="{StaticResource PrimaryHueMidBrush}"/>
<Setter Property="BorderThickness" Value="0"/>
</Style>
</Button.Style>
</Button>
</StackPanel>
</Border>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ContextMenu.Style>
</ContextMenu>
</Window.Resources>
How would I be able to add a name to the Button so I can enable and disable it in my c# (without using binding), I have tried putting x:Name="" but it doesn't work, but if I add a button click it works? I am quite confused, any help would be appreciated!
I still say you should be doing this properly with data-binding, but if you insist...there are a couple of different ways to go about this.
Context menus aren't part of the regular visual tree, so you have to access them directly. Give your context menu a name, and then find the button by traversing its template's visual tree:
// button has to be templated in order for this to work,
// so don't try it in the parent window's constructor
// (add a this.contextMenu.Loaded handler instead if you have to)
var button = this.contextMenu.Template.FindName("openinBrowser", this.contextMenu) as Button;
If your visual tree is particularly complex then a faster option would be to create a boolean resource in your window's resources block:
xmlns:sys="clr-namespace:System;assembly=mscorlib"
<Window.Resources>
<sys:Boolean x:Key="ButtonEnabled">True</sys:Boolean>
</Window.Resources>
...and then bind your button to that dynamically:
<Button x:Name="openinBrowser" IsEnabled="{DynamicResource ButtonEnabled}">
This breaks your "no binding" rule though, which is why I was asking why you're so adamant about not using data-binding...you can still use it, even if you're not binding to the data context. In this scenario you set the value of that resource in your code instead:
this.Resources["ButtonEnabled"] = false;

WPF Button style won't apply to second button

I have two buttons that use a static common style:
<Button x:Name="BtnCreate" Height="22" Width="150" Style="{StaticResource Style.Button.Trash}"/>
<Button x:Name="aefae" Height="22" Width="150" Style="{StaticResource Style.Button.Trash}"/>
The style is very basic:
<Style TargetType="Button" x:Key="Style.Button.Trash"
BasedOn="{StaticResource {x:Type Button}}">
<Setter Property="Content">
<Setter.Value>
<StackPanel Orientation="Horizontal" >
<Image Source="{StaticResource Image.Trash}" Width="22" Height="22"/>
<Label Content="Save" VerticalAlignment="Center" Height="26" />
</StackPanel>
</Setter.Value>
</Setter>
</Style>
The style applies to the first button and display both the image an the text however the second button does not display anything except a grey button.
Why does the second button not use the static style?
As you're trying to add the same Content to two Buttons, elements (present in Style) cannot be added to two different Logical Parents. To avoid this, you can set x:Shared="False" to your style.

Button foreground doesn't change when content is StackPanel

I have a button style defined where the template has a ContentPresenter with a name of "contentPresenter". It then has a trigger set up like this:
<ControlTemplate.Triggers>
<Trigger Property="UIElement.IsEnabled" Value="False">
<Setter Property="TextElement.Foreground" TargetName="contentPresenter" Value="#FF838383" />
</Trigger>
</ControlTemplate.Triggers>
This trigger simply changes the foreground color of a button to gray when the button is disabled. However, I have one button in my application which does not have simple text as its content. The button looks like this:
<Button Grid.Column="3" Grid.Row="3" Grid.ColumnSpan="2"
Margin="120 20 30 10"
Command="{Binding SomeCommand}">
<StackPanel Orientation="Horizontal">
<Image Source="{Binding MyImage}" Margin="0 0 2 0"
Visibility="{Binding ShowMyImage, Converter={StaticResource BooleanToVisibilityConverter}}"/>
<TextBlock Text="{Binding ButtonText}" />
</StackPanel>
</Button>
The foreground of this button is always the same whether the button is disabled or not. I'm thinking it's because the text for the button is in a textblock within the stackpanel in the content presenter, but I don't know how to get the foreground color changes to be applied to the inner textblock.
I tried changing the Property in the trigger to use "TextBlock.Foreground" instead of "TextElement.Foreground". I also tried binding the Foreground of the inner textblock to the foreground color of the closest ancestor of type FrameworkElement like this:
<TextBlock Text="{Binding ButtonText}" Foreground="{Binding RelativeSource={RelativeSource AncestorType={x:Type FrameworkElement}}, Path=(FrameworkElement.Foreground)}" />
None of this worked. What do I need to do to get the foreground color to apply to the TextBlock inside the StackPanel?
Your trigger should be in the Style, and should be setting Foreground on the Button itself, rather than on the ContentPresenter. Then it'll Just Work, with a custom template or with the default template. No need for any extra bindings.
<Style TargetType="Button" x:Key="MyButtonStyle">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Border Background="Beige" BorderBrush="Black" BorderThickness="1" Padding="6,2">
<ContentPresenter
/>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
<Style.Triggers>
<Trigger Property="IsEnabled" Value="False">
<Setter Property="Foreground" Value="#FF838383" />
</Trigger>
</Style.Triggers>
</Style>
Usage:
<Button
IsEnabled="False"
Style="{StaticResource MyButtonStyle}"
>
<StackPanel>
<TextBlock
>Blah Blah</TextBlock>
<Button>X</Button>
</StackPanel>
</Button>
<Button Style="{StaticResource MyButtonStyle}" IsEnabled="False">Testing</Button>
Screenshot (never mind my ugly template):

Setting Button's Content to <Image> via Styles

Can't 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):
Specified element is already the logical child of another element. Disconnect it first.
The style creates one instance of the Image, you cannot use it in two places like this. You can create the image as a separate resource with x:Shared= false and reference it in the style then a new one will be created in every place the style is used.
e.g.
<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>
Already yesterday i found a user with a similar problem: WPF - Change a button's content in a style?
This post got me to this soloution (couldn't post it because of 8 hour limit of stackoverflow -.-)
<Setter Property="ContentTemplate">
<Setter.Value>
<DataTemplate>
<Image Source="{mcWPF:LangRes imgSettings16, Bitmap}" Height="14"/>
</DataTemplate>
</Setter.Value>
</Setter>
Don't know weather this is more clean/dirty/better than H.B.'s soloution

Resources