Setting WPF background Opacity programmatically - c#

I'm working on application which creates a new wpf border component for each row in a database. This means I've got to style the border component in C# rather than XAML (as far as I'm aware). The styling is all good so far apart from trying to set the background opacity.
motherboards.Add(new Border());
Border moboBorder = motherboards[i];
moboBorder.Width = 150;
moboBorder.Height = 150;
moboBorder.BorderBrush = Brushes.Black;
moboBorder.Background = Brushes.White;
moboBorder.CornerRadius = new CornerRadius(10);
moboBorder.Margin = new Thickness(5);
moboBorder.BorderThickness = new Thickness(1);
You can adjust the background opacity in XAML like so
<Border BorderThickness="1" Height="100" Width="100">
<Border.BorderBrush>
<SolidColorBrush Color="Black" Opacity="0.7"/>
</Border.BorderBrush>
</Border>
But as I've said I'm creating the component in C# rather than XAML. I guess this is how you set the value in c#
moboBorder.Background.Opacity = //Value
However, I can't figure out what kind of value it takes, not just a straight up number, nothing from brushes than I can see and nothing like = new Opacity()
I've tried googling around but everything is about setting the opacity for the whole element rather than just the background of it.

A double is certainly a "straight up number"; hover the mouse over the property to see the data type.
The problem (thanks, Clemens) is that you're trying to set the opacity of Brushes.Black, which is a system object and you've got no business doing that.
But you can set the Opacity of a SolidColorBrush that you create yourself.
To create a new semi-opaque white brush:
x.Background = new SolidColorBrush(Colors.White) { Opacity = 0.5 };
See Geoff's answer for how to create a color from an RGB triplet (or ARGB quad) instead of named colors.
Or just keep the existing brush, if you're confident that you didn't get it from Brushes.
Background.Opacity = 0.5;
If you did this, you got it from System.Brushes:
<Window
Background="DeepSkyBlue"
...
If you did this, you didn't:
<Window.Background><SolidColorBrush Color="DeepSkyBlue" /></Window.Background>
That DeepSkyBlue is Colors.DeepSkyBlue; you're creating a new brush with that color.
You should be doing all of this in XAML with bindings instead of creating WPF controls in C#. You'll shoot your eye out, kid.
But it's your eye.

The equivalent of the XAML
<Border.BorderBrush>
<SolidColorBrush Color="Black" Opacity="0.7"/>
</Border.BorderBrush>
in code behind would be
moboBorder.Background = new SolidColorBrush
{
Color = Colors.Black,
Opacity = 0.7
};
In contrast to the predefined Brushes in the Brushes class (which are frozen), the above SolidColorBrush can be changed at any time later, like
moboBorder.Background.Opacity = 0.5;

As #Clemens kindly pointed out in the comments:
You can't set the Opacity of the system's shared brushes directly.
You will need to use a non-shared SolidColorBrush, and then you will be able to set the Opacity of that.
You will be able to change the Opacity from any point in the code, from thereon-in.
E.g.:
moboBorder.Background = new SolidColorBrush(Color.FromRgb(255, 0, 0))
{
Opacity = 0.5 // or whatever opacity between
// 0.0 (0%) and 1.0 (100%)
};
Or
moboBorder.Background = new SolidColorBrush(Color.FromRgb(255, 0, 0));
moboBorder.Background.Opacity = 0.5;
Similar the above example, you could also set the alpha (the opacity) if you're using RGB.
You can use the Color.FromArgb() static method, instead:
moboBorder.Background = new SolidColorBrush(Color.FromArgb(0.5, 255, 0, 0));
Just use a double between 0.0 and 1.0 (as before), as your first argument to the method.
Hope this helps.

Related

WPF - Setting corner radius in code behind

I want to bring a some rectangles to my WPF-Pages, these Rectangles should have rounded corners. To bring a few of the rectangles to the page without having to write every single one in xaml I decided to do it with a loop in the code.
I tried this one:
for (int i = 0; i < 5; i++)
{
Rectangle rect = new Rectangle();
rect.Fill = System.Windows.Media.Brushes.Green;
var style = new Style(typeof(Border));
style.Setters.Add(new Setter(Border.CornerRadiusProperty, new CornerRadius(12.0, 0, 0 , 0)));
rect.Resources.Add(typeof(Border), style);
Grid.SetColumn(rect, 1);
Grid.SetRow(rect, 1);
mainGrid.Children.Add(rect);
}
but the corner radius of my rectangles won´t change. Do you have any suggestion?
Thanks for your help in advance!
To bring a few of the rectangles to the page without having to write every single one in xaml
Good problem to solve.
I decided to do it with a loop in the code
Absolutely bad solution. Use proper MVVM with an <ItemsControl> bound to your list of objects you're trying to display, stored in your view model. And then create a global style sheet and apply it to this either automatically or manually.
Anyway to answer your question, you're creating an unnamed style on Border and applying it to a Rectangle. That will never auto-apply, and good thing, because you reference Border.CornerRadiusProperty which doesn't exist on a Rectangle.
You want to either make your style override the Rectangle's template and add a Border around it, then set its corner border radius, or manually add the border above the rectangle and set its corner radius in your setter (only add the style to the Border's resources).
Your code doesn't really make sense to me though, Rectangle also has corner radius properties, RadiusX and RadiusY, you could just set those if that's what you want.
The rectangle is overflowing. If you do the same thing with a border it will work. When you add the rectangle inside the border you can see what its doing
Rectangle rect = new Rectangle();
rect.Fill = System.Windows.Media.Brushes.Green;
Border b = new Border();
b.Width = 100;
b.Height = 100;
b.Background = Brushes.White;
b.CornerRadius= new CornerRadius(12, 0, 0, 0);
b.BorderThickness = new Thickness(2);
b.BorderBrush = Brushes.Red;
b.Child = rect;//adding this rectangle will show you how the corner is overflowing
grid_Main.Children.Add(b);

How can you outline an ellipse without using stroke property?

What I really want is a way to have a negative stroke Thickness value on a WPF shape such as an ellipse, so that the stoke outline paints outwards towards LEFT and TOP of Shape, rather than inside of the shape, over writing my text when I make the thinkness of the stroke too thick... I want the radius of my ellipse to stay constant, but the stroke to grow outwards with increased thinkness, and the LEFT, TOP placement of the shape to remain contant with the inner fill staying the same size and not getting covered up by stroke as it is increased in size.
I tried DropShadowEffect, but its kind of too blurry and not well defined enough...and looks kind of messy... really I just want a solid line going around the outside of the shape...
As you can see from attached picture above, I tried to put shadow around two the ellipses using this code below. the problem is that I want it to be a solid color around the outside like a scaletransform of another ellipse of a different color.
var e = new Ellipse();
DropShadowEffect effect = new DropShadowEffect();
effect.Color =Colors.Orange;
effect.Direction = 0;
effect.BlurRadius = 30;
effect.ShadowDepth = 4;
effect.Opacity=0;
e.Effect = effect;
t.Text = string.Format("abc");
t.Measure(new Size(gwin.XStep, gwin.YStep));
t.Arrange(new Rect(t.DesiredSize));
e.StrokeThickness = 2;
e.Stroke = Brushes.Black;
canvas.Children.Add(e);
canvas.Children.Add(t);
Another possible direction towards solving the problem:
<Ellipse RenderTransformOrigin="0.5,0.5">
<Ellipse.RenderTransform>
<TransformGroup>
<ScaleTransform/>
</TransformGroup>
</Ellipse.RenderTransform>
</Ellipse>
Convert to c# code and place one scaletransform ellipse centered inside another scaled transform ellipse of different colors... not sure how to set it up though.
Solution:
Based on suggestion below. I tried creating a grid, setting the width and height of the grid to the size of my ellipse, then adding two ellipses to the grid with different colors and one with a margin set to -10. and it works perfectly ... just need to place the larger ellipse with margin -10 behind the other ellipse when adding it to the grid...here's what it looks like now..
Solution is in here somewhere:
g = new Grid();
e = new Ellipse();
h = new Ellipse();
t = new TextBlock();
t.HorizontalAlignment = HorizontalAlignment.Center;
t.VerticalAlignment = VerticalAlignment.Center;
t.FontWeight = FontWeights.ExtraBold;
g.Children.Add(h);
g.Children.Add(e);
g.Children.Add(t);
gwin.canvas.Children.Add(g);
t.Text = String.Format("{0}.{1}", x, y);
g.Width = gwin.XStep;
g.Height = gwin.YStep;
Canvas.SetLeft (g, gwin.X1 + gwin.XStep*x*2);
Canvas.SetTop (g, gwin.Y1 + gwin.YStep*y*2);
e.StrokeThickness = 2;
e.Stroke = Brushes.Black;
h.Margin = new Thickness(-10);
You can use double ellipses inside a grid overlaying each other like this:
<Grid Width="100" Height="100">
<Ellipse Fill="Black" Margin="-10"/>
<Ellipse Fill="Red" />
</Grid>
The size of this compound is still 100x100 even though the first ellipse is bigger and rendered out of its boundaries.
You may also use a Path and then do this
I think there is something like border. Or you can draw one elipse and then a second one in smaller that has the background color.

uwp Expression node fade in animation

I am using the sample on Windows UI dev labs sample gallery. And I used ShyHeader example to put in my app, but I am not using exactly the same code but I actually edited the example according to own needs.
My question is how can I use expression node to fade in a specific XAML element in correspondence to the scroll viewer, I am able to fade out an element with the scroll viewer. but I am not being able to fade in an element from opacity 0 -> opacity 1.
here is my code.
<ScrollViewer x:Name="MyScrollViewer">
<Grid>
<local:MyAdaptiveView Margin="0,300,0,0"
x:Name="AllVideosGridView"/>
<Grid x:Name="Header" Height="300" VerticalAlignment="Top">
<FlipView x:Name="MainFlipView"
</FlipView>
<Grid Background="Blue" Height="150" VerticalAlignment="Bottom" Opacity="0.5" Name="FrontGrid">
</Grid>
</Grid>
</Grid>
</ScrollViewer>
page loaded method
the only important piece of code is only at the very end of this method, the last 4, 5 lines, you can see I am able to fade out element by doing 1- progresNode but my attempt to fade in another element ( frontVisual ) by doing 0+ progressNode doesn't work and frontVisual actually remains at 0 opacity even after I scroll.
private void ShyView_Loaded(object sender, RoutedEventArgs e)
{
// Get the PropertySet that contains the scroll values from MyScrollViewer
_scrollerPropertySet = ElementCompositionPreview.GetScrollViewerManipulationPropertySet(MyScrollViewer);
_compositor = _scrollerPropertySet.Compositor;
// Create a PropertySet that has values to be referenced in the ExpressionAnimations below
_props = _compositor.CreatePropertySet();
_props.InsertScalar("progress", 0);
_props.InsertScalar("clampSize", 150);
_props.InsertScalar("scaleFactor", 0.7f);
// Get references to our property sets for use with ExpressionNodes
var scrollingProperties = _scrollerPropertySet.GetSpecializedReference<ManipulationPropertySetReferenceNode>();
var props = _props.GetReference();
var progressNode = props.GetScalarProperty("progress");
var clampSizeNode = props.GetScalarProperty("clampSize");
var scaleFactorNode = props.GetScalarProperty("scaleFactor");
// Create a blur effect to be animated based on scroll position
var blurEffect = new GaussianBlurEffect()
{
Name = "blur",
BlurAmount = 0.0f,
BorderMode = EffectBorderMode.Hard,
Optimization = EffectOptimization.Balanced,
Source = new CompositionEffectSourceParameter("source")
};
var blurBrush = _compositor.CreateEffectFactory(
blurEffect,
new[] { "blur.BlurAmount" })
.CreateBrush();
blurBrush.SetSourceParameter("source", _compositor.CreateBackdropBrush());
// Create a Visual for applying the blur effect
_blurredBackgroundImageVisual = _compositor.CreateSpriteVisual();
_blurredBackgroundImageVisual.Brush = blurBrush;
_blurredBackgroundImageVisual.Size = new Vector2((float)Header.ActualWidth, (float)Header.ActualHeight);
// Insert the blur visual at the right point in the Visual Tree
ElementCompositionPreview.SetElementChildVisual(Header, _blurredBackgroundImageVisual);
// Create and start an ExpressionAnimation to track scroll progress over the desired distance
ExpressionNode progressAnimation = EF.Clamp(-scrollingProperties.Translation.Y / clampSizeNode, 0, 1);
_props.StartAnimation("progress", progressAnimation);
// Create and start an ExpressionAnimation to animate blur radius between 0 and 15 based on progress
ExpressionNode blurAnimation = EF.Lerp(0, 15, progressNode);
_blurredBackgroundImageVisual.Brush.Properties.StartAnimation("blur.BlurAmount", blurAnimation);
// Get the backing visual for the header so that its properties can be animated
Visual headerVisual = ElementCompositionPreview.GetElementVisual(Header);
// Create and start an ExpressionAnimation to clamp the header's offset to keep it onscreen
ExpressionNode headerTranslationAnimation = EF.Conditional(progressNode < 1, 0, -scrollingProperties.Translation.Y - clampSizeNode);
headerVisual.StartAnimation("Offset.Y", headerTranslationAnimation);
// Create and start an ExpressionAnimation to scale the header during overpan
ExpressionNode headerScaleAnimation = EF.Lerp(1, 1.25f, EF.Clamp(scrollingProperties.Translation.Y / 50, 0, 1));
headerVisual.StartAnimation("Scale.X", headerScaleAnimation);
headerVisual.StartAnimation("Scale.Y", headerScaleAnimation);
//Set the header's CenterPoint to ensure the overpan scale looks as desired
headerVisual.CenterPoint = new Vector3((float)(Header.ActualWidth / 2), (float)Header.ActualHeight, 0);
// Get the backing visual for the photo in the header so that its properties can be animated
Visual photoVisual = ElementCompositionPreview.GetElementVisual(MainFlipView);
// Create and start an ExpressionAnimation to opacity fade out the image behind the header
ExpressionNode imageOpacityAnimation = 1 - progressNode;
photoVisual.StartAnimation("opacity", imageOpacityAnimation);
// Get the front visual for the photo in the header so that its properties can be animated
Visual frontVisual = ElementCompositionPreview.GetElementVisual(FrontGrid);
// Create and start an ExpressionAnimation to opacity fade out the image behind the header
ExpressionNode imageOpacityAnimation2 = 0 + progressNode;
frontVisual.StartAnimation("opacity", imageOpacityAnimation2);
}
Note the behavior I actually want is that when I scroll down then FlipView should fade out and when I scroll up to the top it should fade in, which is working perfectly, but along with it I want FrontGrid to be exactly opposite, i.e: fade in on scroll down and fade out on scroll up.
Thanks in advance
Your expression looks OK.
Note the Opacity you are animating with Composition is the Opacity of Visual. However, the Opacity of 0.5 you are setting on FrontGrid XAML is from UIElement. Doing so will break the Composition opacity expression animation.
The fix is simple - Try getting the Visual of your FrontGrid right after InitializeComponent and set its Opacity to 0.5 there (i.e. frontVisual.Opacity = 0.5) instead of setting it in XAML.
You will see this kind of "weird" behaviors starting from the Anniversary Update, due to a XAML-Composition Interop Behavior change.
For a full explanation, please read this official document.
In short, XAML doesn't know if Composition has changed the Opacity, it still thinks it should be 0.5 as it was last set. So it will try to override and cause the animation to fail. This happens to a few more properties like Offset and Size too.
My advice is if you go Composition, try going Composition all the way. :)

C# WPF - Adorner ZIndex

I have a Grid with a Adorner to provide some drawn pattern. See img: http://imgur.com/D649W
My problem is that this Adorner(dots on the Grid) is layered on top of everything. The white square are draggable but now when the Adorner are on top, I can't drag. I would like the layer to be behind every component added to the Grid. Any suggestions on how I can set the ZIndex?
Thanks.
Code below:
MyAdorner ad = new MyAdorner(grid);
AdornerLayer adLayer = AdornerLayer.GetAdornerLayer(grid);
adLayer.Add(ad);
I push my Button and this is adding the MyAdorner to the grid. MyAdorner looks like this:
public MyAdorner(Grid adornedGrid)
: base(adornedGrid) {
Height = adornedGrid.Height;
Width = adornedGrid.Width;
brush = new VisualBrush();
brush.Stretch = Stretch.Fill;
brush.TileMode = TileMode.Tile;
brush.Viewport = new Rect(0, 0, SnapDistance, SnapDistance);
brush.ViewportUnits = BrushMappingMode.Absolute;
brush.Viewbox = new Rect(0, 0, SnapDistance, SnapDistance);
brush.ViewboxUnits = BrushMappingMode.Absolute;
ellipse = new Ellipse() { Fill = new SolidColorBrush(Colors.Blue), Width = 2, Height = 2 };
brush.Visual = ellipse;
}
protected override void OnRender(System.Windows.Media.DrawingContext drawingContext) {
Pen renderPen = new Pen(new SolidColorBrush(Colors.Black), 0);
drawingContext.DrawRectangle(brush, renderPen, new Rect(new Point(0, 0), AdornedElement.DesiredSize));
}
If your problem is that the adorner is covering the elements you want to manipulate so that they become un-draggable etc, set .IsHitTestVisible = False on the adorner.
You can also set the adorner's opacity to some semi-transparent value to see the background through it if that is desirable.
Is this what you're looking for?
Panel.SetZIndex(ad, 20)
Attached properties of the framework are usually asignable from static methods of the UIElement that holds it.
EDIT:
Possible alternative: - make your own Panel
Easy and dirty way to make sure that your wanted elements are ALWAYS on top:
Declare a static in a Util library:
public static int ZIndexCount;
Then when you want an element on top you simply do:
SetZIndex(_viewbox, Util.ZIndexCount++);
Of course, if your application runs 5 years without being interrupted the ZIndexCount will go back to 0...
It works like a charm in my applications.
I know this is quite old but I thought I try anyway:
You can add a new AdornerDecorator to you visual tree hierarchy to render the controls at the right level. By default the root of the tree provides the AdornerDecorator but you can add as many as you want and your the components you add will be rendered in them. For more information - see here
<Grid>
<AdornerDecorator>
...your Adorners render here
</AdornerDecorator>
</Grid>
https://wangmo.wordpress.com/2008/10/19/relations-between-adorner-adornerlayer-and-adornerdecorator/

WPF: the right way to scale a path?

I have a path (looks like an oval):
<Path Data="Bla Bla"/>
Now I want to scale the path's width and height to whatever I like. I found a way:
<Grid Width="400" Height="50">
<Viewbox Stretch="Fill">
<Path Data="Bla Bla"/>
</Viewbox>
</Grid>
And this works, but I'm wondering if this is the most efficient way to do this? (I had to introduce a grid and viewbox to do this)
Another way to Scale a Path is to use RenderTransform or LayoutTransform
<Path Data="Bla Bla"
RenderTransformOrigin="0.5, 0.5">
<Path.RenderTransform>
<ScaleTransform ScaleX="1.5" ScaleY="1.5"/>
</Path.RenderTransform>
</Path>
just FYI, since ViewBox uses ScaleTransform inside it it's basically just as good performance-wise.
You basically have 3 ways to scale a Path:
Wrap it into a ViewBox
Apply a ScaleTransform
Explicitly set a Width and a Height
Method 1. and 2. will yield the same result, while 3. is slightly different because the shape will change size, but the stroke will keep the original Thickness (so it's not really a zoom).
Method 1. would be appropriate when you have an area of a given size that you want to fill. On the other hand method 2. will be useful to enlarge (or reduce) the path by a given amount, for ex. two times the original size.
You could do it programmaticaly, like
http://social.msdn.microsoft.com/Forums/vstudio/en-US/a0d473fe-3235-4725-aa24-1ea9307752d3/how-to-rendertransform-in-code-behind-c?forum=wpf
kUIWEB:kArrow mArrow = new kUIWEB:kArrow();
mArrow.Width=30;
mArrow.Height=30;
mArrow.RenderTransformOrigin=new Point(0.5, 0.5);
ScaleTransform myScaleTransform = new ScaleTransform();
myScaleTransform.ScaleY = 1;
myScaleTransform.ScaleX = 1;
RotateTransform myRotateTransform = new RotateTransform();
myRotateTransform.Angle = 0;
TranslateTransform myTranslate = new TranslateTransform ();
myTranslate.X = 12;
myTranslate.X = 15;
SkewTransform mySkew = new SkewTransform ();
mySkew.AngleX=0;
mySkew.AngleY=0;
// Create a TransformGroup to contain the transforms
// and add the transforms to it.
TransformGroup myTransformGroup = new TransformGroup();
myTransformGroup.Children.Add(myScaleTransform);
myTransformGroup.Children.Add(myRotateTransform);
myTransformGroup.Children.Add(myTranslate);
myTransformGroup.Children.Add(mySkew);
// Associate the transforms to the object
mArrow.RenderTransform = myTransformGroup;

Categories

Resources