Bind the scale of a Button to an image - wpf

I have a simple window with an image and a button. When the user resizes the window, I would like the button to be resized with the image in the exact same proportions. Below is an example of the desired behaviour I would like to have. The button around the head of the dog just extends and translates with the image.
I managed to have the above behaviour with a "Path" (above in blue), but I didn't manage to get the same behaviour with a button. I would like to perform some actions when the user clicks on the button.
Here is the xaml code I used for the working "Path" senario:
<Grid>
<Canvas x:Name="polylineCanvas" Grid.Row="1">
<Image x:Name="imgTraining"
Width="{Binding ActualWidth, ElementName=polylineCanvas, Mode=OneWay}"
Height="{Binding ActualHeight, ElementName=polylineCanvas, Mode=OneWay}"
Stretch="Uniform"
HorizontalAlignment="Left"
VerticalAlignment="Top">
</Image>
<Path Stroke="Blue" StrokeThickness="3">
<Path.Data>
<PathGeometry x:Name="polyline">
<PathGeometry.Transform>
<ScaleTransform
ScaleX="{Binding ActualWidth, ElementName=imgTraining}"
ScaleY="{Binding ActualHeight, ElementName=imgTraining}"/>
</PathGeometry.Transform>
</PathGeometry>
</Path.Data>
</Path>
</Canvas>
</Grid>
I tried to apply the same logic by adding a button instead of a Path. In this case, the button streches to the size of the window (but not to the size of the image):
Here is the xaml code I added for the button:
<Button x:Name="buttSelection" Opacity="0.5" Background="#FF000CFF">
<Button.LayoutTransform>
<ScaleTransform
ScaleX="{Binding ActualWidth, ElementName=imgTraining}"
ScaleY="{Binding ActualHeight, ElementName=imgTraining}"/>
</Button.LayoutTransform>
</Button>
Questions:
How could I scale my button in the same proportion as the image?
How could I set the size and position of this button to only be a part of the image (and not to be as big as the image itself)?
Thanks a lot for the support!
PS: I am very new to wpf/xaml, so there is a big chance that I am not doing things in the "intended way" or that there is a completely different solution.

You should put both the Image and the Button in a common Viewbox, which would automatically scale them together. There is usually no need to bind the size of an element to the actual size of another. This is done by using appropriate layout panels.
Inside the Viewbox, there would be a Grid as common parent, and a Canvas to position the Button. The Button Template would contain a Border around a ContentPresenter that could optionally show the Button's Content.
<Grid>
<Viewbox>
<Grid>
<Image x:Name="imageTraining"/>
<Canvas>
<Button x:Name="buttonSelection" Width="200" Height="200"
Canvas.Left="200" Canvas.Top="200">
<Button.Template>
<ControlTemplate TargetType="Button">
<Border BorderThickness="10"
BorderBrush="Blue"
Background="Transparent">
<ContentPresenter
HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
</Border>
</ControlTemplate>
</Button.Template>
</Button>
</Canvas>
</Grid>
</Viewbox>
</Grid>

Related

Draw a line under button

I am trying to draw a line under the button, well in fact, last element within the button. The button has three element inside in vertical: image, label, and finally the line I am trying to put. Line must be the same widht than button. Below the code that is not working (line does not appear):
<Button Name="btnDelete" HorizontalAlignment="Center" Margin="30,10" Command="{Binding DeleteCommand}">
<Button.Template>
<ControlTemplate>
<StackPanel Orientation="Vertical">
<Image Height="36" Width="36" Stretch="UniformToFill" Source="/MyResources;component/PNG/Delete.png"/>
<Label HorizontalAlignment="Center">Delete</Label>
<Line Stroke="Orange" X1="0" Y1="25" X2="{Binding ElementName=btnDelete, Path=Width}" Y2="25" />
</StackPanel>
</ControlTemplate>
</Button.Template>
</Button>
If you just want a straight Line then use a Border. If you just need it horizontal then use it like :
<Button Name="btnDelete" HorizontalAlignment="Center" Margin="30,10" Command="{Binding DeleteCommand}">
<Button.Template>
<ControlTemplate>
<Border BorderBrush="Orange" BorderThickness="0 0 0 3">
<StackPanel>
<Image Height="36" Width="36" Stretch="UniformToFill" Source="/MyResources;component/PNG/Delete.png"/>
<Label HorizontalAlignment="Center">Delete</Label>
</StackPanel>
</Border>
</ControlTemplate>
</Button.Template>
</Button>
Use Margin and Padding to adjust it - when needed.
Also u should use Paths instead of Image. You can convert them directly in XAML-Paths with Incscape.
Additional Information Path
A Path is a good way to show Icons in XAML. They can look like:
<Path Stroke="Black" Fill="Gray"
Data="M 10,100 C 10,300 300,-200 300,100" />
You can give them different Brushes and they scale very well in the most scenarious. Inkscape has a good feature - to create the Path out of your Image (svg / png / jpg etc).
There are also Icon-Packs that allready have them like font awesome.

WPF / Xaml, vertical aligment of LineGeomtry inside grid not working properly

I try to get into creation of custom controls with for WPF. I found many good
tutorials and advises on the web so I started width a really simple example to get
my hands dirty and get some practice. I figured out that the issue stumbled across
is not really related to the subject of custom controls. So I extracted the xaml code to a simple wpf form.
<Window x:Class="WpfVerticalAigmentTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="200" Width="200">
<Grid>
<Grid Height="40" Background="LightCyan" VerticalAlignment="Center">
<Path Stroke="Red"
StrokeThickness="20" VerticalAlignment="Center" >
<Path.Data>
<LineGeometry StartPoint="0,0" EndPoint="100,0"></LineGeometry>
</Path.Data>
</Path>
</Grid>
</Grid>
My expectation was to get a line centered in the grid and claiming the half of the stroke thickness on each side from the center. But as the linked image shows differs from my expectation.
"Resulting visualization"
So it look like I missed a detail about the line shape or linegeomtry. How do I get the the line displayed as shown in the following image?
"Expected result"
You need to match the Width and Height of the LineGeometry to the Width and Height of the Path and set the VerticalAlignment property to Bottom:
<Grid Height="20" Width="200" Background="LightCyan" VerticalAlignment="Center">
<Path Stroke="Red" StrokeThickness="20" VerticalAlignment="Bottom">
<Path.Data>
<LineGeometry StartPoint="0,0" EndPoint="200,0"></LineGeometry>
</Path.Data>
</Path>
</Grid>
If your goal is your the expectaions, and not the way how u have reached this, I could prefer to you this:
<Grid>
<Grid Height="40" Background="LightCyan" VerticalAlignment="Center">
<Border BorderThickness="10" VerticalAlignment="Center" BorderBrush="Red" />
</Grid>
</Grid>
The problem here is that the starting point of the XY Coordinates of the Path starts on the top left, and the stroke expands in both directions but thereby only makes the Path bigger to the bottom (I can't really tell you why, but that's just what seems to happen).
You can see this pretty good in the Design View:
To work around this simply move your Y Coordinates down half of the stroke size.
<Grid Height="40"
VerticalAlignment="Center"
Background="LightCyan">
<Path VerticalAlignment="Center"
Stroke="Red"
StrokeThickness="20">
<Path.Data>
<LineGeometry StartPoint="0,10" EndPoint="100,10" />
</Path.Data>
</Path>
</Grid>
Or wrap it in another control (Canvas is the commonly used controls for Paths) with the desired height:
<Grid Height="40"
VerticalAlignment="Center"
Background="LightCyan">
<Canvas Height="20" VerticalAlignment="Center">
<Path Stroke="Red"
StrokeThickness="20">
<Path.Data>
<LineGeometry StartPoint="0,10" EndPoint="100,10" />
</Path.Data>
</Path>
</Canvas>
</Grid>
And you are good to go:

Control to use for Reusable container for content/content template?

I am creating a container whose style will be used across the application. It essentially is a 'pop up' but won't spawn in a new window. The general structure of my app is one NavigationWindow and many pages. So I get started with the following Template, defined in my Resource Dictionary:
<ControlTemplate x:Key="RainbowModalTemplate" TargetType="{x:Type Control}">
<Canvas Height="540" Canvas.Left="492" Canvas.Top="296" Width="945">
<Border x:Name="Modal" Height="540" Width="945" Background="#ec2016" BorderBrush="White" BorderThickness="2" CornerRadius="15" Style="{DynamicResource RainbowModalBox}">
<Border.Clip>
<RectangleGeometry RadiusX="15" RadiusY="15" Rect="0,0,945,540"/>
</Border.Clip>
<Image Source="Resources/RainbowModal/rainbow.png" Height="247" Width="947" Margin="0,0,0,0" VerticalAlignment="Bottom" d:LayoutOverrides="Height" Stretch="UniformToFill" Canvas.Left="-2" Canvas.Top="293" ClipToBounds="True" />
</Border>
</Canvas>
</ControlTemplate>
So when I want to 'consume' this, I want to be able to implement this control but provide my own content inside, (buttons, text, etc). However because I am new to WPF I am unsure what control or controls to use, and what structure to lay this out as. Below is sample 'consumer' of the object. Someone will click a button in the application and that will set this objects' visibility to be Visible :
<Control x:Name="RequestMoreInfoModal" Template="{DynamicResource RainbowModalTemplate}" Canvas.Left="494" Canvas.Top="250" Visibility="Collapsed"></Control>
I know this probably isn't the most kosher way to do this, so I am open to suggestion. My specific concerns:
I know "Control" isn't the right type. But I don't know what is appropriate and it appears Canvas and other controls do not allow Templating. What control should I use?
how do I implement this Template and also allow the consumer to define their own content within the Template?
What I eneded up doing is using a ControlTemplate and ContentPresenter.
Here is the definition of the reusable content in my ResourceDictionary:
<ControlTemplate x:Key="RainbowModal" TargetType="ContentControl">
<Canvas>
<Border x:Name="Modal" Height="540" Width="945" Background="#ec2016" BorderBrush="White" CornerRadius="15" BorderThickness="2" Style="{DynamicResource RainbowModalBox}">
<Border.Clip>
<RectangleGeometry
RadiusX="{Binding CornerRadius.TopLeft, RelativeSource={RelativeSource AncestorType={x:Type Border}}}"
RadiusY="{Binding RadiusX, RelativeSource={RelativeSource Self}}"
Rect="0,0,945,540"/>
</Border.Clip>
<Canvas>
<Image Source="Resources/RainbowModal/rainbow.png" Height="247" Width="947" Margin="0,0,0,0" VerticalAlignment="Bottom" Stretch="UniformToFill" Canvas.Left="-2" Canvas.Top="293" ClipToBounds="True" />
<ContentPresenter/>
</Canvas>
</Border>
</Canvas>
</ControlTemplate>
And here is the 'consumption' of that content.
<ContentControl x:Name="RequestMoreInfoModal" Canvas.Left="489" Canvas.Top="122" Template="{StaticResource RainbowModal}" Visibility="Collapsed">
<Canvas>
<TextBlock FontSize="78" Foreground="White" Width="903" Canvas.Top="28" Canvas.Left="20" Height="298" Text="Scan your card to receive an email with more information." TextWrapping="Wrap" FontFamily="Serif72 Beta" TextAlignment="Center" />
<Button Width="250" Height="76" Content="CLOSE" Margin="350,350" Style="{DynamicResource PurpleInfoButton}" FontSize="28" Click="Button_Click_1" ></Button>
</Canvas>
</ContentControl>

WPF: Resizing a circle, keeping the center point instead of TopLeft?

I'd like to resize a circle on my canvas with the help of a slider. This circle can be moved around on the canvas by some drag&drop stuff I did in code behind, so its position is not fixed.
I have bound the slider's value to an ellipse's height and width. Unfortunately, when I use the slider, the circle gets resized with its top left point (actually the top left point of the rectangle it's sitting in) staying the same during the operation.
I would like to resize it with its center point being constant during the operation. Is there an easy way to do this in XAML? BTW, I already tried ScaleTransform, but it didn't quite do what I wanted.
Thanks a bunch! :-)
Jan
<Canvas x:Name="MyCanvas">
<!-- this is needed for some adorner stuff I do in code behind -->
<AdornerDecorator Canvas.Left="10"
Canvas.Top="10">
<Ellipse x:Name="myEllipse"
Height="{Binding Path=Value, ElementName=mySlider}"
Width="{Binding Path=Value, ElementName=mySlider}"
Stroke="Aquamarine"
Fill="AliceBlue"
RenderTransformOrigin="0.5 0.5">
<Ellipse.RenderTransform>
<RotateTransform Angle="{Binding Path=Value, ElementName=myRotationSlider}" />
</Ellipse.RenderTransform>
</Ellipse>
</AdornerDecorator>
<Slider x:Name="mySlider"
Maximum="100"
Minimum="0"
Width="100"
Value="10"
Canvas.Left="150"
Canvas.Top="10" />
<Slider x:Name="myRotationSlider"
Maximum="360"
Minimum="0"
Width="100"
Value="0"
Canvas.Left="150"
Canvas.Top="50" />
</Canvas>
You can bind your Canvas.Left and Canvas.Top to your Height and Width via a ValueConverter.
Specifically (edit):
Create a property each for the Canvas.Left and Canvas.Top and bind to these.
Store the old values for Width and Heigth or the old slider value.
Whenever the slider is changed, get the incremental change "dx" by subtracting the stored value.
(Don't forget to update the stored value...)
Add dx to Width and Height property.
And, as Will said, add dx/2*-1 to Canvas.Left and Canvas.Top properties.
Does that make sense?
The problem is that you are using the SLIDER to adjust the width and height. Width and height are not calculated around RenderTransformOrigin; only RenderTransforms use that value.
Here's a corrected version (brb, kaxaml):
<Canvas x:Name="MyCanvas">
<!-- this is needed for some adorner stuff I do in code behind -->
<AdornerDecorator Canvas.Left="50" Canvas.Top="50">
<Ellipse
x:Name="myEllipse"
Width="10"
Height="10"
Fill="AliceBlue"
RenderTransformOrigin="0.5 0.5"
Stroke="Aquamarine">
<Ellipse.RenderTransform>
<TransformGroup>
<RotateTransform Angle="{Binding Path=Value, ElementName=myRotationSlider}"/>
<ScaleTransform
CenterX=".5"
CenterY=".5"
ScaleX="{Binding Path=Value, ElementName=mySlider}"
ScaleY="{Binding Path=Value, ElementName=mySlider}"/>
</TransformGroup>
</Ellipse.RenderTransform>
</Ellipse>
</AdornerDecorator>
<Slider
x:Name="mySlider"
Width="100"
Canvas.Left="150"
Canvas.Top="10"
Maximum="10"
Minimum="0"
SmallChange=".01"
Value="1"/>
<Slider
x:Name="myRotationSlider"
Width="100"
Canvas.Left="150"
Canvas.Top="50"
Maximum="360"
Minimum="0"
Value="0"/>
</Canvas>
Of course, this will probably not work for you. Why? Well, the ScaleTransform I used zooms not only the circle but also the border; as the circle gets bigger the border does as well. Hopefully you won't care about this.
Also, realize when combining transforms (scale then rotate in this case) that they are applied in order, and one may affect how another is done. In your case, you would not notice this. But if, say, you were doing a rotate and translate, the order would be relevant.
Ah, what was I thinking? Just stick the ellipse in a Grid (simplest solution but other containers would work). The grid automatically takes care of centering the ellipse as it is resized. No need for any value converters! Here's the code:
<Canvas x:Name="MyCanvas">
<!-- this is needed for some adorner stuff I do in code behind -->
<Grid Width="100" Height="100">
<AdornerDecorator>
<Ellipse
x:Name="myEllipse"
Width="{Binding Path=Value, ElementName=mySlider}"
Height="{Binding Path=Value, ElementName=mySlider}"
Fill="AliceBlue"
RenderTransformOrigin="0.5 0.5"
Stroke="Aquamarine">
<Ellipse.RenderTransform>
<RotateTransform Angle="{Binding Path=Value, ElementName=myRotationSlider}"/>
</Ellipse.RenderTransform>
</Ellipse>
</AdornerDecorator>
</Grid>
<Slider
x:Name="mySlider"
Width="100"
Canvas.Left="150"
Canvas.Top="10"
Maximum="100"
Minimum="0"
Value="10"/>
<Slider
x:Name="myRotationSlider"
Width="100"
Canvas.Left="150"
Canvas.Top="50"
Maximum="360"
Minimum="0"
Value="0"/>
</Canvas>
Since you're using a Canvas, the location an element has is the location. If you want the Top,Left position to change you need to do it yourself. If you were using another Panel type, like a Grid, you could change the alignment of your Ellipse to place it in the same relative location no matter what the size. You could get that effect by adding a Grid inside your AdornerDecorator and centering the Ellipse but you'd also need to set the AdornerDecorator or Grid to a fixed size because they won't stretch in a Canvas.
The best solution you could use would be a ScaleTransform applied to the RenderTransform property with a RenderTransformOrigin of 0.5,0.5. You said you had problems with ScaleTransform but not what the problem was.
Wrap your Ellipse in a Grid of the maximum size. As long as it is smaller, the Ellipse will be centered in the Grid:
<Grid
Canvas.Left="10"
Canvas.Top="10"
Width="100"
Height="100">
<AdornerDecorator>
<Ellipse x:Name="myEllipse"
Height="{Binding Path=Value, ElementName=mySlider}"
Width="{Binding Path=Value, ElementName=mySlider}"
Stroke="Aquamarine"
Fill="AliceBlue"
RenderTransformOrigin="0.5 0.5">
<Ellipse.RenderTransform>
<RotateTransform Angle="{Binding Path=Value, ElementName=myRotationSlider}" />
</Ellipse.RenderTransform>
</Ellipse>
</AdornerDecorator>
</Grid>
You may need to adjust your dragging logic to handle dragging the Grid instead of the Ellipse itself.
I've found a very easy way to do this in plain XAML: set Margin="-1000000". Read more here: Positioning an element inside the Canvas by its center (instead of the top left corner) using only XAML in WPF

Use UIElement as Clip in WPF

Please pardon my ignorance- I'm very new to WPF.
I am looking to implement a minor, visual effect in my application that gives the look of "inner" rounded corners. The window in question has a dark border that encapsulates several UIElements, one of which is a StatusBar, located at the bottom of the window. This StatusBar has a dark background that matches the window's border. Above the StatusBar is a content view, which is currently a Grid- its background is semi-transparent (I think that this is something of a constraint- you can see through the content view to the desktop below). I would like for the content view (represented by the transparent, inner area in the figure below) to have the look of rounded corners, though I expect to have to sort of create the illusion myself.
(Can't post the image because I'm a lurker and not a poster- please find the drawing here)
My first approach was to add a Rectangle (filled with the same, dark color as the border) immediately above the StatusBar and to assign a Border with rounded corners to its OpacityMask (similar to the solution proposed by Chris Cavanagh**). Sadly, the effect that is produced is the exact opposite of that which I am trying to achieve.
I understand that the Clip property can be of use in this sort of situation, but it seems to me that using any sort of Geometry will prove to be inadequate as it won't be dynamically sized to the region in which it resides.
EDIT: Including my XAML:
<Grid Background="{StaticResource ClientBg}" Tag="{Binding OverlayVisible}" Style="{StaticResource mainGridStyle}">
<DockPanel LastChildFill="True">
<!-- Translates to a StackPanel with a Menu and a Button -->
<local:FileMenuView DockPanel.Dock="Top" />
<!-- Translates to a StatusBar -->
<local:StatusView DockPanel.Dock="Bottom" />
<!-- Translates to a Grid -->
<local:ContentView />
</DockPanel>
</Grid>
Any pointers are more than welcome- I'm ready to provide more indepth detail if necessary.
** http://www.dotnetkicks.com/wpf/WPF_easy_rounded_corners_for_anything
EDIT: Now I got what you mean. In fact you can use Path + OpacityMask approach. You have to draw "inverted" path, to use it as opacity mask. But I have simpler and faster solution for you :). Use Border + CornerRadius, and fill the gaps with solid paths. Just try the following code in Kaxaml and let me know if this is what you were looking for:
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Width="240"
Height="320"
AllowsTransparency="True"
Background="Transparent"
WindowStyle="None">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="24"/>
<RowDefinition Height="*"/>
<RowDefinition Height="24"/>
</Grid.RowDefinitions>
<Border Background="Black"/>
<Border Grid.Row="1" BorderBrush="Black" BorderThickness="5">
<Grid>
<Border Background="White" CornerRadius="0, 0, 5, 5" Opacity="0.7"/>
<Path
Width="15"
Height="15"
HorizontalAlignment="Left"
VerticalAlignment="Bottom"
Data="M10,10 L5,10 L5,5 C4.999,8.343 6.656,10 10,10 z"
Fill="Black"
Stretch="Fill"/>
<Path
Width="15"
Height="15"
HorizontalAlignment="Right"
VerticalAlignment="Bottom"
Data="M10,10 L5,10 L5,5 C4.999,8.343 6.656,10 10,10 z"
Fill="Black"
Stretch="Fill">
<Path.RenderTransform>
<TransformGroup>
<ScaleTransform ScaleX="-1"/>
<TranslateTransform X="15"/>
</TransformGroup>
</Path.RenderTransform>
</Path>
</Grid>
</Border>
<Border Grid.Row="2" Background="Black"/>
</Grid>
</Window>
PS: You can simplify this solution by avoiding render transforms, but you got the idea.

Resources