Apply Brush to Two Objects At Once - wpf

I'd like to apply a Brush (LinearGradientBrush in this case) to two or more objects (TextBlocks) at once. The effect that I'd like is something like this:
Edit
I cannot simply apply the same brush to both objects, as this will make both of them start red and go to blue (instead of the second one starting at a shade of purple).
I'm sure I'm overlooking something quick-n-easy...
Thanks,
wTs

I did it like this:
<Border Height="100" Width="600" >
<Border.OpacityMask>
<VisualBrush>
<VisualBrush.Visual>
<StackPanel>
<TextBlock FontSize="85.333" FontFamily="Calibri" TextAlignment="Right">
The big first line
</TextBlock>
<TextBlock TextWrapping="Wrap" Margin="0,0,8,0" FontSize="32" FontFamily="Calibri" Text="The small second line" TextAlignment="Right" />
</StackPanel>
</VisualBrush.Visual>
</VisualBrush>
</Border.OpacityMask>
<Border.Background>
<LinearGradientBrush EndPoint="0.974,0.49" StartPoint="0,0.457">
<GradientStop Color="#FFFD0202"/>
<GradientStop Color="#FF0234FD" Offset="1"/>
</LinearGradientBrush>
</Border.Background>
</Border>
So, a border whose background is filled with the gradient from blue to red. The only visible part of the gradient is the text in the opacity mask.
Maybe some simpler control than the border would be even better.
The remaining issue is that one has to size the container control explicitly, as it has no content.

What about using an ObjectDataProvider that exposes a method that returns the brush you want based on 3 integers, the starting x position of the brush, the current x position of the brush, and the ending x position of the brush (I could see use cases where you might want four parameters, x start, x end, x current start, x current end, but the 3 parameter will work for the case you have asked for). You can either statically assign these integers based on the layout of your control or use databinding for the parameters.
If you are unfamiliar with ObjectDataProvider and binding to method parameters for this class, i suggest going here and here

Declare the brush into the window (or application) resources and bind the Foreground property of the two textblocks with the brush.

Related

WPF Custom Border - bracket style

I would like to create a custom border around a content, that the upper and lower side of the border is not continuous, it should have a style like bracket as below. (inside the "bracket border" the content should be placed e.g. grid, stackpanel, etc.)
Note that the height of the right and the left border can be changed depending on the content's height, whereas the top and the bottom should have a standard width.
[ sample content ]
In order to achieve this, I separated the view in a 3 columns grid:
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="22px"></ColumnDefinition>
<ColumnDefinition Width="*"></ColumnDefinition>
<ColumnDefinition Width="22px"></ColumnDefinition>
</Grid.ColumnDefinitions>
<Border Grid.Column="0" BorderBrush="Blue" BorderThickness="6px 6px 0px 6px"></Border>
<Border Grid.Column="1" BorderBrush="Transparent" BorderThickness="6px">
<!--Place for the actual content of the border-->
<TextBlock Text="Test" FontSize="15"></TextBlock>
</Border>
<Border Grid.Column="2" BorderBrush="Blue" BorderThickness="0px 6px 6px 6px"></Border>
</Grid>
Is there another approach for achieving this style?
One possible solution is to write your own Border based on a Decorator.
An implementation (for a different border) can be found in How can I draw a border with squared corners in wpf?
One simple trick is try setting some LinearGradientBrush for the BorderBrush. If your text has a fixed width, it will look best at all time. However when the text's width may change, the horizontal lines (at 2 ends) will shrink/extend at some ratio. That's because we set some Offset for the GradientStop and it's pity that this Offset can only be set based on some ratio (from 0 to 1) with the width of the whole Brush (which is exactly the width of the Border when the background is stretched). Note that the MappingMode cannot change this behavior, it just works for StartPoint and EndPoint.
Here is the pure XAML code:
<Border VerticalAlignment="Center" HorizontalAlignment="Center"
BorderThickness="3" Padding="5,0,5,0">
<TextBlock Text="Square bracket border here" FontSize="30"
HorizontalAlignment="Center"/>
<Border.BorderBrush>
<LinearGradientBrush StartPoint="0,1" EndPoint="1,1">
<GradientStop Offset="0.03" Color="Blue"/>
<GradientStop Offset="0.03" Color="Transparent"/>
<GradientStop Offset="0.97" Color="Transparent"/>
<GradientStop Offset="0.97" Color="Blue"/>
</LinearGradientBrush>
</Border.BorderBrush>
</Border>
You can change the Offset of the first 2 GradientStops to what you want, the Offset of the remaining GradentStops should be the subtraction of the first's Offset from 1.
If using some code behind, you can pinpoint exactly the length of the horizontal lines (at the 2 ends). That way we need some Binding between the Offset and the ActualWidth of the Border. Next we need some Converter here, this Converter will convert the ActualWidth and the desired exact length to the correct ratio. So when the text width changes, the length of the horizontal lines will always be some fixed value.
You can try the following XAML code:
<Grid>
<Border BorderBrush="Black" BorderThickness="1"/>
<TextBlock Text="sample content"/>
<Border BorderBrush="White" BorderThickness="0,1,0,1" Margin="8,0,8,0"/>
</Grid>
Second border's color "White" can be replaced with the actual background color. "Transparent" color will not help.
Thanks,
RDV

Why is the fill of an Ellipse not applied when the Stretch property is set inside a VisualBrush?

I'm working on a custom control and I have a VisualBrush with the Visual property as such:
<VisualBrush.Visual>
<Grid>
<Ellipse Stretch="Uniform" Stroke="OrangeRed" StrokeThickness="1">
<Ellipse.Fill>
<RadialGradientBrush GradientOrigin="0.5,0.5">
<GradientStop Color="Yellow" Offset="0" />
<GradientStop Color="Orange" Offset="1" />
</RadialGradientBrush>
</Ellipse.Fill>
</Ellipse>
<Ellipse Stretch="Uniform">
<Ellipse.Fill>
<RadialGradientBrush GradientOrigin="0.5, 0.05" RadiusX=".7" RadiusY=".5" >
<GradientStop Color="White" Offset=".10" />
<GradientStop Color="Transparent" Offset="1" />
</RadialGradientBrush>
</Ellipse.Fill>
</Ellipse>
</Grid>
</VisualBrush.Visual>
When the Stretch property is set to Uniform instead of using the RadialGradientBrush I created, it somehow creates a SolidColorBrush using the Stroke color. However, when I explicitly set the Width and Height properties of the Ellipse instead of using the Stretch property, I get the gradient I expected.
Any ideas of what's going weird here?
EDIT: I just observed the behavior occurs when I enclose the Ellipse inside of a ViewBox.
I'm not sure what you're using the ViewBox for in your above example, but I think some of the strange behaviour you're seeing is a result of not setting the size on the root element for your VisualBrush.
In the documentation for VisualBrush.Visual, there's a paragraph that mentions sizing (added emphasis):
When you define a new Visual for a VisualBrush and that Visual is a
UIElement (such as a panel or control), the layout system runs on the
UIElement and its child elements when the AutoLayoutContent property
is set to true. However, the root UIElement is essentially isolated
from the rest of the system; styles, storyboards, and external layout
dictated by the parent where the brush is applied cannot permeate this
boundary. Therefore, you should explicitly specify the size of the
root UIElement, because its only parent is the VisualBrush and
therefore it cannot automatically size itself to the area being
painted. For more information about layout in Windows Presentation
Foundation (WPF), see the Layout.
If I run your code above, my ellipse is completely filled with the stroke colour, presumably because the the layout is calculated with the smallest value for the ellipse, so the stroke is large enough to cover ellipse content/fill (which is then upscaled to the fill the viewport so it looks like the stroke is the fill colour).
If I give the root element some arbitrary size on which to base the layout <Grid Width="100" Height="100">...</grid> I start to see the stroke and fill colours, rendered with relative sizes.

wpf gradient brush that spans multiple elements

Suppose there is an element with irregular shape composed of other elements with arbitrary nesting:
<Window.Resources>
<RadialGradientBrush x:Key="brush">
<GradientStop Color="Black" Offset="0" />
<GradientStop Color="White" Offset="1" />
</RadialGradientBrush>
</Window.Resources>
<StackPanel Name="element">
<StackPanel.Effect>
<DropShadowEffect ShadowDepth="0" BlurRadius="10" />
</StackPanel.Effect>
<Rectangle Name="child1" Height="100" Margin="10" Stroke="Black" Fill="{StaticResource brush}" />
<Grid>
<Rectangle Name="child2" Height="100" Margin="10" Stroke="Black" Fill="{StaticResource brush}" />
</Grid>
</StackPanel>
All parts are interactive (i.e a child can be a real control).
How can I fill backgrounds of children with a single radial gradient that spans all of them (should look like as if it is sized to element).
UPDATE: StackPanel has a shadow which should be drawn around children.
One possible solution is to generate gradients with Radius and Origin/Center bound to element's and child's properties with appropriate conversions, but such approach would be rather complex and expensive.
Finally, I went with transformed gradients route except instead of bindings and converters I was able to elegantly solve it by creating background Transformation in ArrangeOverride of child elements and exposing it via dependency property.
Actual RadialGradientBrush binds its Transform to BackgroundTransform by searching for ancestor with matching type.
This assumes that one can modify/wrap child classes which is true in my case. It can be made more flexible with attached properties and a bit more work.
Actual code is in this gist.

Dynamic Brushes in XAML

I have a definition for a data template that looks as follows:
<DataTemplate DataType="{x:Type HeatMap:BlockItem}">
<Grid Visibility="{Binding IsVisible}">
<Border Name="BlockBorder" Width="{Binding Width}" Height="{Binding Height}">
<Border.Background>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="{Binding Colour}" Offset="1"/>
<GradientStop Color="White"/>
</LinearGradientBrush>
</Border.Background>
</Border>
</Grid>
</DataTemplate>
As can be seen, BlockItem has a property of type Color called Colour which is bound to the first color of the LinearGradientBrush which fills a border, making it look like a filled rectangle.
Now I don't always want Linear Gradient Brushes to style the fill of this rectangle. Some rectangles on my canvas may need to be filled with SolidBrushes, for example. I considered creating a Brush property on the BlockItem class instead of a Color property and binding the entire Border.Background to that, but there are 2 problems with this:
I don't know how the XAML should look to specify a binding to the entire object Background property.
In the code where I create BlockItems, if I instantiate a new Brush for every single BlockItem (bear in mind, there maybe be many drawn on a canvas at a time), will this not make it really inefficient and slow?
1) You can bind the Background directly to a brush on your BlockItem:
<Border Name="BlockBorder" Background="{Binding MyBackgroundBrush}">
2) You could bind to a static resource, or create a static brush for your BlockItem.
Background="{StaticResource myStaticBrush}"

WPF: Button template w/ cornerRadius and Bevel looks wrong

I changed the ControrTemplate of a button, gave it a border with CornerRadius and BevelBitmpaEffect. Looks decent enough for the minimal effort. Put it on a colored background and then the problem becomes apperent.
The corner where the lightangle is coming from there is a white snip with a right angle corner. Possibly coming from the light effect but very obvious with a cornerRadius. I don't suppose I could do anything about it ( aside from the obvious like not using a cornerRadius )?
EDIT:
This code should generate the same problem for you
<Style x:Key="TabButtons" TargetType="Button">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Border CornerRadius="8"
SnapsToDevicePixels="True"
Name="BtnBorder"
Width="80"
Height="35"
BorderThickness="1"
BorderBrush="DarkBlue">
<Border.Background>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="LightBlue" Offset="0" />
<GradientStop Color="DarkBlue" Offset="1" />
</LinearGradientBrush>
</Border.Background>
<Border.BitmapEffect>
<BevelBitmapEffect BevelWidth="5"
EdgeProfile="CurvedOut"
LightAngle="135"
Relief="0.1"
Smoothness="1" />
</Border.BitmapEffect>
<ContentPresenter Name="BtnContent" VerticalAlignment="Center" HorizontalAlignment="Center" ContentSource="Content" />
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
Use this button on a LightBlue Background for example
<Border Background="LightBlue" >
<Button Style={StaticResource TabButtons} >Test</Button>
</Border>
I can't imagine what the problem exactly looks like, but here is one suggestion - try setting the SnapsToDevicePixels to true for the affected button or perhaps the entire window.
The problem might stem from the fact that WPF by default wants to do device independent rendering. Which causes control edges to slightly "bleed" to adjacent pixels due to width/height and DPI/pixels not aligning exactly. Setting SnapsToDevicePixels to true, will force WPF to render exactly for the device pixels and the "bleeding" effect will dissapear...
EDIT:
I tried out the code you provided and I guess the "white snip" is the white(ish) pixels around the corners?
Well the problem here stems from antialiasing, which also lightens the pixels inside the corners. Because you use a dark tone, those lighter pixels stand out and the button doesn't look so nice.
I'm not sure if this can be considered a bug. You would think that antialising will do it's magic on the pixels that make up the corner and outside of the corner, but every pixel inside of the corner should be colored with the background color.
Then again this might be by design, that antialiasing has to mess with the pixels inside the corner as well otherwise you don't get the required effect...
Anyway there are two workarounds:
1) Give the border the following property RenderOptions.EdgeMode="Aliased". This will turn off antialiasing (0% white(ish) pixels), but the controll will look very jaggedy.
2) Use two borders. The outer border will be defined just like you have defined your current border, only set the Background property to just DarkBlue. Then for this outer border create another border as a child element. For this inner border set CornerRadius=7, RenderOptions.EdgeMode="Aliased" and define the Background with the LinearGradientBrush. The inner border will contain the ContentPresenter. The code will look like this:
<Border CornerRadius=8 Background=DarkBlue>
<Border CornerRadius=7 RenderOptions.EdgeMode="Aliased">
<Border.Background>
...
</Border.Background>
<ContentPresenter />
</Border>
</Border>
It won't get rid of the white pixels a 100%, but this is the best compromise I think. With the naked eye I couldn't see any white pixels, but when I zoomed in with the magnifier tool I counted only 2 pixels per corner and only at the bottom corners. Before it was something like 8 pixels per corner. At least the outer border is still antialiased and the control doesn't look jaggedy.
The BevelBitmapEffect didn't make any difference to the appearance of the control so I just ommited it.

Resources