I created an adorner on a WPF line element, because there was neet to add some text.
Now, when this line is moved, the adorner does not "follow" the line automatically. In fact, it does not refresh itsef:
here black curves is the Control drawing, and the red "120 m" is the adorner one.
Some code
void SegmentLine_Loaded(object sender, RoutedEventArgs e)
{
AdornerLayer aLayer = AdornerLayer.GetAdornerLayer(this);
if (aLayer != null)
{
aLayer.Add(new TextAdorner(this));
}
}
class TextAdorner : Adorner
{
public TextAdorner(UIElement adornedElement)
: base(adornedElement)
{
}
protected override void OnRender(DrawingContext drawingContext)
{
SegmentLine segment = (this.AdornedElement as SegmentLine);
if (segment != null)
{
Rect segmentBounds = new Rect(segment.DesiredSize);
var midPoint = new Point(
(segment.X1 + segment.X2) / 2.0,
(segment.Y1 + segment.Y2) / 2.0);
var lineFont = // get line font as Font
FormattedText ft = new FormattedText(
string.Format("{0} m", segment.Distance),
Thread.CurrentThread.CurrentCulture,
System.Windows.FlowDirection.LeftToRight,
new Typeface(lineFont.FontFamily.ToString()),
ligneFont.Size, Brushes.Red);
drawingContext.DrawText(ft, midPoint);
}
}
}
Why MeasureOverride, etc aren't being called
Your adorner's MeasureOverride, ArrangeOverride, and OnRender aren't being called because your SegmentLine control is never changing size or position:
Since your SegmentLine doesn't implement MeasureOverride, it always has the default size assigned by the layout engine.
Since your SegmentLine doesn't implement ArrangeOverride or manipulate any transforms, its position is always exactly the upper-left corner of the container.
The Adorner's MeasureOverride, ArrangeOverride and OnRender are only called by WPF under these conditions:
The AdornedElement changes size or position (this the most common case), or
One of the Adorner's properties chagnes and that property is marked AffectsMeasure, AffectsArrange, or AffectsRender, or
You call InvalidateMeasure(), InvalidateArrange(), or InvalidateVisuaul() on the adorner.
Because your SegmentLine never changes size or position, case 1 doesn't apply. Since you don't have any such properties on the Adorner and don't call InvalidateMeasure(), InvalidateArrange() or InvalidateVisual(), the other cases don't apply either.
Precise rules for Adorner re-measure
Here are the precise rules for when an adorned element change triggers a call to Adorner.MeasureOverride:
The adorned element must force a layout pass by invalidating its Measure or Arrange in response to some event. This could be triggered automatically by a change to a DependencyProperty with AffectsMeasure or AffectsArrange, or by a direct call to InvalidateMeasure(), InvalidateArrange() or InvalidateVisual().
The adorned element's Measure and Arrange methods must not be called directly from user code between the invalidation and the layout pass. In other words, you must wait for the layout manager to do the job.
The adorned element must make a non-trivial change to either its RenderSize or its Transform.
The combination of all transforms between the AdornerLayer and the adorned element must be affine. This will generally be the case as long as you are not using 3D.
Your SegmentLine is just drawing the line in a new place rather than updating its own dimensions, thereby omitting my requirement #3 above.
Recommendation
Normally I would recommend your adorner have AffectsRender DependencyProperties bound to the SegmentLine's properties, so any time X1, Y1, etc change in the SegmentLine they are also updated in the Adorner which causes the Adorner to re-render. This provides a very clean interface, since the adorner can be used on any control that has properties X1, Y1, etc, but it is less efficient than tightly coupling them.
In your case the adorner is clearly tightly bound to your SegmentLine, so I think it makes just as much sense to call InvalidateVisual() on the adorner from the SegmentLine's OnRender(), like this:
public class SegmentLine : Shape
{
TextAdorner adorner;
...
protected override void OnRender(DrawingContext drawingContext)
{
base.OnRender(drawingContext);
if(adorner==null)
{
var layer = AdornerLayer.GetAdornerLayer(this); if(layer==null) return;
adorner = new TextAdorner(this);
... set other adorner properties and events ...
layer.Add(adorner);
}
adorner.InvalidateVisual();
}
}
Note that this doesn't deal with the situation where the SegmentLine is removed from the visual tree and then added again later. Your original code doesn't deal with this either, so I avoided the complexity of dealing with that case. If you need that to work, do this instead:
public class SegmentLine : Shape
{
AdornerLayer lastLayer;
TextAdorner adorner;
...
protected override void OnRender(DrawingContext drawingContext)
{
base.OnRender(drawingContext);
var layer = AdornerLayer.GetAdornerLayer(this);
if(layer!=lastLayer)
{
if(adorner==null)
{
adorner = new TextAdorner(this);
... set other adorner properties and events ...
}
if(lastLayer!=null) lastLayer.Remove(adorner);
if(layer!=null) layer.Add(adorner);
lastLayer = layer;
}
adorner.InvalidateVisual();
}
}
How is the line being moved? Does the MeasureOverride or ArrangeOverride of the adorner get invoked after the move? OnRender will only get invoked if the visual is invalidated (e.g. invalidatevisual) so I'm guessing that the render isn't being invalidated.
May be you wanted to use segmentBounds to define midPoint? Otherwise what is it doing there? Looks like you are defining midPoint relative to not rerendered segment.
idiot fix, but it works
AdornerLayer aLayer;
void SegmentLine_Loaded(object sender, RoutedEventArgs e)
{
aLayer = AdornerLayer.GetAdornerLayer(this);
if (aLayer != null)
{
aLayer.Add(new TextAdorner(this));
}
}
protected override void OnRender(DrawingContext drawingContext)
{
base.OnRender(drawingContext);
if (aLayer != null)
{
aLayer.Update();
}
}
Now, the problem is that when I click on a the adorner the control itself does not recieve the hit...
Related
This is just example to learn from.
I want create custom control with completely different looks. Hence, according to https://learn.microsoft.com/en-us/dotnet/framework/wpf/controls/control-authoring-overview, I derive from FrameworkElement
and override OnRender method, also OverriderMesure and ArrangeOverride if needed.
Now I want implement mouse interaction, for example: on hover change color from red to blue. How I should do it?
public class Box : FrameworkElement
{
private static Color defaultColor = Colors.Red;
public static DependencyProperty ColorProperty = DependencyProperty.Register("Color", typeof(SolidColorBrush), typeof(Box),
new FrameworkPropertyMetadata(new SolidColorBrush(defaultColor), FrameworkPropertyMetadataOptions.AffectsRender));
public SolidColorBrush Color
{
get { return (SolidColorBrush)GetValue(ColorProperty); }
set { SetValue(ColorProperty, value); }
}
static Box()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(Box), new FrameworkPropertyMetadata(typeof(Box)));
}
protected override void OnRender(DrawingContext drawingContext)
{
// It's just example, I know shape is wayyy too simple to involve custom render.
drawingContext.DrawRectangle(Color, null, new Rect(0, 0, ActualWidth, ActualWidth));
}
protected override void OnMouseEnter(MouseEventArgs e)
{
Color = new SolidColorBrush(Colors.Blue); // Set to color
}
protected override void OnMouseLeave(MouseEventArgs e)
{
Color = new SolidColorBrush(defaultColor); // Back to default
}
protected override Size MeasureOverride(Size constraint)
{
...
}
protected override Size ArrangeOverride(Size finalSize)
{
...
}
}
So far I deduce:
Normally, if I had derive from Control, I would have use VSM for this. Unfortunately VSM isn't available until ControlTemplate hierarchy tree, so controls which have Template property. So if I decided to draw my control by myself I need use for this Routed Events, in this particular example OnMouseEnter(MouseEventArgs), OnMouseLeave(MouseEventArgs) and some dependency property, like code above.
It this right approach? Please remember it's for learning purpose so FrameworkElement as base is obligatory.
I can see some drawbacks, becouse If we want control onHover color (in code above is harcoded to blue) I need mess around with code behind, or create another dependency property for this.
Unfortunately VSM isn't available until ControlTemplate hierarchy tree, so controls which have Template property.
This it not true.
You can use VSM normally, with some small changes. Read: https://msdn.microsoft.com/en-us/library/system.windows.visualstatemanager(v=vs.110).aspx#Examples. Take a closer look on example.
An Adorner is defined over part of an Image. The required behavior is as follows:
When the mouse is over the image area, including the Adorner area, the Adorner appears.
When the mouse leaves the image and Adorner area, the Adorner dissapears.
Adorner appearing and disappearing is to be through a fade in / out animation, accordingly.
A click on the Adorner area must raise event AdornerClicked
A click on the area over the Image which is not hidden by the adorner, must rais ImageClicked.
A naive implementation
Attach an animation on the Adorner opacity on the Image's MouseEnter and MouseLeave events, and attach Click events for each. This however causes the Adorner to disappear when the mouse is directly above it (as a MouseLeave is triggered on the Image below), violating requirement number 1.
A possible amendment to the naive implementation is to set IsHitTestVisible=false on the Adorner. However, no clicks are then captured by the Adorner, violating requirement number 4.
What is the correct pattern which will fulfill the requirements?
A bit old question but I've just had the same problem and could not find an answer so here's what I've come up with.
So the problem is that the control and its adorner are overlapping and setting the adorner to visible triggers a MouseLeave on the adorned control because it is now covered by the adorner.
The solution is to react on every MouseEnter and MouseLeave on both the adorned control and its adorner(s) and do a hit test manually. If any of them are hit then the adorner(s) should be visible otherwise collapsed.
So you need to be able to get the adorners from the adorned control and vica versa. Getting the adorned control from the adorner is no problem (use the AdornedElement property) but getting the adorners for a control is not provided by the framework (AFAIK) so I use a dictionary that maps my controls to a list of their adorners.
Here's the code inside my Panel-derived class (that contains and arranges my controls and their adorners):
private readonly Dictionary<Control, List<Adorner>> _controlToAdornersMap;
...
private void CreateMyControl()
{
var control = new MyControl();
control.MouseEnter += OnMyControlMouseEnterOrLeave;
control.MouseLeave += OnMyControlMouseEnterOrLeave;
Children.Add(control);
AddAdorners(control);
}
private void AddAdorners(Control control)
{
var myAdorner = new MyAdorner(control);
myAdorner.MouseEnter += OnMyAdornerMouseEnterOrLeave;
myAdorner.MouseLeave += OnMyAdornerMouseEnterOrLeave;
var adornerLayer = AdornerLayer.GetAdornerLayer(control);
adornerLayer.Add(myAdorner);
_controlToAdornersMap[control] = new List<Adorner> {myAdorner};
}
private void OnMyControlMouseEnterOrLeave(object sender, MouseEventArgs e)
{
HitTestAndSetAdornersVisibility((MyControl)sender, e);
}
private void OnMyAdornerMouseEnterOrLeave(object sender, MouseEventArgs e)
{
var adorner = (Adorner)sender;
HitTestAndSetAdornersVisibility((MyControl)adorner.AdornedElement, e);
}
private void HitTestAndSetAdornersVisibility(MyControl control, MouseEventArgs e)
{
var adorners = _controlToAdornersMap[control];
var hitTestSubjects = new List<UIElement> { control }.Concat(adorners);
var hit = hitTestSubjects.Any(i => VisualTreeHelper.HitTest(i, e.GetPosition(i)) != null);
SetAdornersVisibility(adorners, hit ? Visibility.Visible : Visibility.Collapsed);
}
private static void SetAdornersVisibility(IEnumerable<Adorner> adorners, Visibility visibility)
{
if (adorners != null)
foreach (var adorner in adorners)
adorner.Visibility = visibility;
}
I'm trying to create an overlay in wpf (with darkening background), similar to the ones you can find on the web to popup images.
I would like it to be reusable in more than 1 part of the application, with diffent types of content.
this is the temporary code of the constructor of the adorner class (just to try)
private readonly Grid _grid = new Grid();
public DarkOverlayAdorner(UIElement adornedElement, Object content) :
base(adornedElement)
{
_grid.Background = new SolidColorBrush(Color.FromArgb(99, 0, 0, 0));
IsHitTestVisible = true;
var visual = content as UIElement;
if (visual != null)
_grid.Children.Add(visual);
}
In addition in the class (of course), I have the ovverrides of MeasureOverride and ArrangeOverride to give the adorner the correct size of the adorned element, GetVisualChild, and VisualChildCount...
The problem here is that the adorner is correctly shown, but no events or behaviour are applied on the adorned element. For example:
AdornerLayer layer = AdornerLayer.GetAdornerLayer(textBoxProva);
layer.Add(new DarkOverlayAdorner(textBoxProva, new Button{Content = "prova"}));
The button here is shown, but I can-t click the button and no effects on button mouseover are applied.
I still can't figure out the problem.
Ok, I've lost a lot of time trying to figure out what was the problem.
In the end I found the solution:
If you want the element added to react to events, I think that the element must be bound to the visual tree of the adorner.
The way to do it is to use a VisualCollection, intitialized to the adorner itself:
VisualCollection visualChildren;
FrameworkElement #object;
public DarkOverlayAdorner(UIElement adornedElement) :
base(adornedElement)
{
visualChildren = new VisualCollection(this);
#object = new Button {Content = "prova"};
visualChildren.Add(#object);
}
protected override Visual GetVisualChild(int index)
{
return visualChildren[index];
}
This way the events are correctly routed.
You might want to take a look at the ChildWindow control in the Extended WPF Toolkit. It is a control that pops up a Window with a modal background effect, and you can specify the content to put inside the Window.
Ok,
So I have a situation, where an border is being scaled (sometimes by a large amount) and translated. Inside the border is a grid, and inside the grid are two images, one is a photo and is stretched to the size of the border, and the other, I intend on being an icon, which needs to be a fixed size in the bottom left hand corner.
The problem is, that I want to remove the effect scaling is having on the icon. This is because I've given the icon a fixed size and would like it to remain that size, but unfortunately the scaling from the border is propagating down the the children of the border and effecting them also.
So I've tried using an attached property, similar to this pixel snapping artical (http://blogs.msdn.com/b/devdave/archive/2008/06/22/using-an-attached-dependencyproperty-to-implement-pixel-snapping-as-an-attached-behavior.aspx), but it doesn't seem to make a difference. When steped through, the elements which are being modified in LayoutUpdate always seem to have the identity matrix for the render transform anyway, before I've set it.
I guess I'm miss-interperating how render transforms are applied to children maybe?
Anyway, this is what I have (Also, I know this (if it worked) would remove translation too, which isn't what I want!):
public static readonly DependencyProperty IsConstantSizeProperty =
DependencyProperty.RegisterAttached(
"ConstantWidth",
typeof(bool),
typeof(ItemsControlEX),
new PropertyMetadata(new PropertyChangedCallback(IsConstantSizeChanged)));
private static List<FrameworkElement> m_constSizeObjects = new List<FrameworkElement>();
private static void IsConstantSizeChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
{
bool isConstantWidth = (bool)args.NewValue;
if (isConstantWidth)
{
FrameworkElement el = (FrameworkElement)obj;
m_constSizeObjects.Add(el);
el.LayoutUpdated += new EventHandler(el_LayoutUpdated);
el.Unloaded += new RoutedEventHandler(el_Unloaded);
}
}
static void el_Unloaded(object sender, RoutedEventArgs e)
{
FrameworkElement el = (FrameworkElement)sender;
el.Unloaded -= new RoutedEventHandler(el_Unloaded);
el.LayoutUpdated -= new EventHandler(el_LayoutUpdated);
m_constSizeObjects.Remove(el);
}
static void el_LayoutUpdated(object sender, EventArgs e)
{
foreach (FrameworkElement el in m_constSizeObjects)
{
MatrixTransform trans = new MatrixTransform();
trans.Matrix = Matrix.Identity;
el.RenderTransform = trans;
}
}
public static void SetIsConstantWidth(UIElement element, Boolean value)
{
element.SetValue(IsConstantSizeProperty, value);
}
public static Boolean GetIsConstantWidth(UIElement element)
{
return (Boolean)element.GetValue(IsConstantSizeProperty);
}
I'm thinking I'm probably thinking about this in completely the wrong way maybe. I guess the sensible solution would be to refactor to remove the need for scaling, but I guess I was just after a quicker solution that I can use until I have time.
Any help is appreciated! :)
Thanks!
Andy.
If you are only scaling (I assume fixed aspect ratio) that seems overly complicated, why not place the photo in a ViewBox container? Place the ViewBox (containing the photo) and the icon (in that order) in a parent grid.
Make the icon relative to the bottom
left using alignment and margin
settings
Resize the viewbox to scale your image.
The grid will shrink to fit the viewbox size. The icon will remain relative to the grid bottom-left.
Your pixel snapping behaviour should work on a ViewBox.
If you need a specific example, please provide some of your Xaml to work from.
I am trying to make a nice "drag and drop zone" in WPF that is displayed in the adorner layer when something is being dragged into the main application. The problem is that I do not get any events from my adorner, even though it according to documentation should receive all input events since it is in a higher z-order.
To debug my problem I created a really simple example where I have a user control with only a button in it. This user control is displayed in the adorner layer, but I cannot click the button. Why? What have I done wrong?
My adorner class is constructed like this:
public ShellOverlayAdorner(UIElement element, AdornerLayer adornerLayer)
:base(element)
{
_adornerLayer = adornerLayer;
_overlayView = new AdornedElement();
_overlayView.AllowDrop = true;
_adornerLayer.Add(this);
}
and is created in the main window by
private void Window_Loaded(object sender, RoutedEventArgs e)
{
adornerLayer = AdornerLayer.GetAdornerLayer(MyTopGridWithButtonInIt);
ShellOverlayAdorner shell = new ShellOverlayAdorner(MyTopGridWithButtonInIt, adornerLayer);
}
I do not get any events at all from my control, i.e. no mouse clicks, mouse over, button clicks. I cannot even click the button in the adorner layer. What have I done wrong?
I don't know if you already tried that:
If you want the element added to react to events, I think that the element must be bound to the visual tree of the adorner.
The way to do it is to use a VisualCollection, intitialized to the adorner itself, or at least, this way it seems to be working:
VisualCollection visualChildren;
FrameworkElement #object;
public CustomAdorner(UIElement adornedElement) :
base(adornedElement)
{
visualChildren = new VisualCollection(this);
#object = new Button {Content = "prova"};
visualChildren.Add(#object);
}
protected override Visual GetVisualChild(int index)
{
return visualChildren[index];
}
This way the events are correctly routed.
I just had the same issue. Following the advice from MSDN sorted it for me:
Adorners receive input events just
like any other FrameworkElement.
Because an adorner always has a higher
z-order than the element it adorns,
the adorner receives input events
(such as Drop or MouseMove) that may
be intended for the underlying adorned
element. An adorner can listen for
certain input events and pass these on
to the underlying adorned element by
re-raising the event.
To enable pass-through hit testing of
elements under an adorner, set the hit
test IsHitTestVisible property to
false on the adorner.
i.e In the adorner itself, make sure IsHitTestVisible = false