/// <summary> /// Binds to specific events of the provided CoreWindow /// </summary> /// <param name="nativeWindow">A reference to <see cref="CoreWindow"/> or <see cref="UIElement"/> class.</param> /// <exception cref="ArgumentNullException">Is thrown when <paramref name="nativeWindow"/> is null.</exception> /// <exception cref="ArgumentException">Is thrown when <paramref name="nativeWindow"/> is not a <see cref="CoreWindow"/> and not an <see cref="UIElement"/></exception> protected override void BindWindow(object nativeWindow) { if (nativeWindow == null) throw new ArgumentNullException("nativeWindow"); var window = nativeWindow as CoreWindow; if (window != null) { windowSize = new Size2F((float)window.Bounds.Width, (float)window.Bounds.Height); var position = window.PointerPosition; pointerPosition = new Vector2((float)position.X/windowSize.Width, (float)position.Y / windowSize.Height); window.PointerPressed += HandleWindowPointerEvent; window.PointerReleased += HandleWindowPointerEvent; window.PointerWheelChanged += HandleWindowPointerEvent; window.PointerMoved += HandleWindowPointerEvent; window.SizeChanged += window_SizeChanged; return; } uiElement = nativeWindow as FrameworkElement; if (uiElement != null) { windowSize = new Size2F((float)uiElement.ActualWidth, (float)uiElement.ActualHeight); uiElement.Loaded += HandleLoadedEvent; uiElement.SizeChanged += HandleSizeChangedEvent; uiElement.PointerPressed += HandleUIElementPointerEvent; uiElement.PointerReleased += HandleUIElementPointerEvent; uiElement.PointerWheelChanged += HandleUIElementPointerEvent; uiElement.PointerMoved += HandleUIElementPointerEvent; uiElement.PointerEntered += HandleUIElementPointerEvent; return; } throw new ArgumentException("Should be an instance of either CoreWindow or UIElement", "nativeWindow"); }
public override void SetValue(NativeView view, object value) { switch (value) { case null: view.SetValue(DependencyProperty, null); break; case NativeBinding binding: binding.Mode = IsTwoWay ? BindingMode.TwoWay : BindingMode.OneWay; view.SetBinding(DependencyProperty, binding); break; default: if (!ValueType.IsEnum) { value.TryChangeType(ValueType, out value); } value = Converter == null ? value : Converter.Invoke(value); if (value.GetType() == PropertyType) { view.SetValue(DependencyProperty, value); } break; } }
internal static Thickness?GetPadding(this IFrameworkElement frameworkElement) { switch (frameworkElement) { case Grid g: return(g.Padding); case StackPanel sp: return(sp.Padding); case Control c: return(c.Padding); case ContentPresenter cp: return(cp.Padding); case Border b: return(b.Padding); case Panel p: return(p.Padding); } return(null); }
public static T GetElementOfTypeByName <T>(this Windows.UI.Xaml.FrameworkElement parent, string elementName) where T : FrameworkElement { Queue <Windows.UI.Xaml.FrameworkElement> elementQueue = new Queue <Windows.UI.Xaml.FrameworkElement>(); elementQueue.Enqueue(parent); while (elementQueue.Count > 0) { var element = elementQueue.Dequeue(); if (element is T) { if (element.Name == elementName) { return(element as T); } } for (int i = 0; i < VisualTreeHelper.GetChildrenCount(element); i++) { var child = VisualTreeHelper.GetChild(element, i); var t = child as T; if (t != null && t.Name == elementName) { return(t); } elementQueue.Enqueue((Windows.UI.Xaml.FrameworkElement)child); } } return(null); }
public static Rect GetElementRect(Windows.UI.Xaml.FrameworkElement element) { Windows.UI.Xaml.Media.GeneralTransform transform = element.TransformToVisual(null); Point point = transform.TransformPoint(new Point()); return(new Rect(point, new Size(element.ActualWidth, element.ActualHeight))); }
private bool GoToStateInternal(FrameworkElement stateGroupsRoot, string stateName, bool useTransitions) { VisualStateGroup group; VisualState state; return (TryGetState(stateGroupsRoot, stateName, out group, out state) && this.GoToStateCore(null, stateGroupsRoot, stateName, group, state, useTransitions)); }
public static BitmapImage ImageFromRelativePath(FrameworkElement parent, string path) { var uri = new Uri(parent.BaseUri, path); BitmapImage result = new BitmapImage(); result.UriSource = uri; return result; }
//DoubleTappedRoutedEventArgs public UwpTapEventArgs(Windows.UI.Xaml.FrameworkElement element, Windows.UI.Xaml.Input.DoubleTappedRoutedEventArgs args, int numberOfTaps) { ViewPosition = element.GetXfViewFrame(); //Touches = new Xamarin.Forms.Point[] { args.GetPosition(null).ToXfPoint() }; Touches = new Xamarin.Forms.Point[] { args.GetPosition(element).ToXfPoint() }; NumberOfTaps = numberOfTaps; }
public static void UpdateCanvasSize(FrameworkElement root, FrameworkElement output, FrameworkElement inkCanvas) { output.Width = root.ActualWidth; output.Height = root.ActualHeight / 2; inkCanvas.Width = root.ActualWidth; inkCanvas.Height = root.ActualHeight / 2; }
private void MenuControl_DataContextChanged(FrameworkElement sender, DataContextChangedEventArgs args) { var propertyChanged = PropertyChanged; if (propertyChanged != null) { propertyChanged(this, new PropertyChangedEventArgs(nameof(ConcreteDataContext))); } }
private bool FindStoreArea(FrameworkElement feItem) { var foundArea = false; var areaName = TryGetArea(feItem); if (areaName != null) { foundArea = true; // Update elements visibility based on previous displayed area if (_previousArea == null || !_previousArea.Equals(areaName)) { // Hide the previous ad if (_previousArea != null) { ShowAd(_previousArea, Visibility.Collapsed); } _previousArea = areaName; // Show the new ad ShowAd(areaName, Visibility.Visible); } } return(foundArea); }
private static void ApplyTheme(FrameworkElement targetElement, Uri dictionaryUri) { if (targetElement == null) return; try { ThemeResourceDictionary themeDictionary = null; if (dictionaryUri != null) { themeDictionary = new ThemeResourceDictionary(); themeDictionary.Source = dictionaryUri; // add the new dictionary to the collection of merged dictionaries of the target object targetElement.Resources.MergedDictionaries.Insert(0, themeDictionary); } // find if the target element already has a theme applied List<ThemeResourceDictionary> existingDictionaries = (from dictionary in targetElement.Resources.MergedDictionaries.OfType<ThemeResourceDictionary>() select dictionary).ToList(); // remove the existing dictionaries foreach (ThemeResourceDictionary thDictionary in existingDictionaries) { if (themeDictionary == thDictionary) continue; // don't remove the newly added dictionary targetElement.Resources.MergedDictionaries.Remove(thDictionary); } } finally { } }
private static FrameworkElement ScalingFrameworkElement(FrameworkElement element) { var compositeTransform = element.RenderTransform as CompositeTransform; switch ((int)compositeTransform.Rotation) { case -90: case 90: case 270: case -270: { element.Width = element.ActualWidth / 2; element.Height = element.ActualHeight / 2; } break; case 0: case 180: case -180: { element.Width = element.ActualWidth * 2; element.Height = element.ActualHeight * 2; } break; case -360: case 360: { compositeTransform.Rotation = 0; element.Width = element.ActualWidth * 2; element.Height = element.ActualHeight * 2; } break; } return element; }
private async Task RenderUIElement(FrameworkElement elm, string fileName, int width, int height) { await System.Threading.Tasks.Task.Delay(TimeSpan.FromSeconds(1)); using (InMemoryRandomAccessStream ms = new InMemoryRandomAccessStream()) { var renderTargetBitmap = new RenderTargetBitmap(); await renderTargetBitmap.RenderAsync(elm); var pixels = await renderTargetBitmap.GetPixelsAsync(); var logicalDpi = DisplayInformation.GetForCurrentView().LogicalDpi; var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, ms); encoder.SetPixelData( BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint)renderTargetBitmap.PixelWidth, (uint)renderTargetBitmap.PixelHeight, logicalDpi, logicalDpi, pixels.ToArray()); await encoder.FlushAsync(); await X.Services.Image.Service.Instance.GenerateResizedImageAsync(width, elm.ActualWidth, elm.ActualHeight, ms, fileName + ".png", Services.Image.Service.location.TileFolder, height); } }
private void OnDataContextChanged(FrameworkElement sender, DataContextChangedEventArgs args) { var m = this.DataContext as MessageRecord; if (m != null) { this.MessageRecord = m; VisualStateManager.GoToState(this, m.IsOutgoing ? "Outgoing" : "Incoming", true); if (m.IsFailed) { VisualStateManager.GoToState(this, "Failed", true); } else { if (!m.IsOutgoing) VisualStateManager.GoToState(this, "None", true); else if (m.IsPending) VisualStateManager.GoToState(this, "Pending", true); else if (m.IsDelivered) VisualStateManager.GoToState(this, "Delivered", true); else VisualStateManager.GoToState(this, "Sent", true); } if (m.IsKeyExchange) { VisualStateManager.GoToState(this, "KeyExchange", true); } } }
internal static async Task Render(CompositionEngine compositionEngine, SharpDX.Direct2D1.RenderTarget renderTarget, FrameworkElement rootElement, Line line) { var rect = line.GetBoundingRect(rootElement).ToSharpDX(); var stroke = await line.Stroke.ToSharpDX(renderTarget, rect); if (stroke == null || line.StrokeThickness <= 0) { return; } var layer = line.CreateAndPushLayerIfNecessary(renderTarget, rootElement); renderTarget.DrawLine( new Vector2( rect.Left + (float)line.X1, rect.Top + (float)line.Y1), new Vector2( rect.Left + (float)line.X2, rect.Top + (float)line.Y2), stroke, (float)line.StrokeThickness, line.GetStrokeStyle(compositionEngine.D2DFactory)); if (layer != null) { renderTarget.PopLayer(); layer.Dispose(); } }
public static bool IsItemVisible(this FrameworkElement container, FrameworkElement element) { var elementBounds = element.TransformToVisual(container).TransformBounds(new Rect(0, 0, element.ActualWidth, element.ActualHeight)); var containerBounds = new Rect(0, 0, container.ActualWidth, container.ActualHeight); return (elementBounds.Top < containerBounds.Bottom && elementBounds.Bottom > containerBounds.Top); }
/// <summary>Creates the default UI element generators.</summary> /// <param name="view">The view.</param> /// <returns>The generators.</returns> public static Dictionary<string, IControlGenerator> GetDefaultGenerators(FrameworkElement view) { var list = new Dictionary<string, IControlGenerator>(); list.Add("p", new ParagraphGenerator()); list.Add("div", new ParagraphGenerator()); list.Add("blockquote", new ParagraphGenerator()); list.Add("h1", new ParagraphGenerator { FontSize = 1.6 }); list.Add("h2", new ParagraphGenerator { FontSize = 1.4 }); list.Add("h3", new ParagraphGenerator { FontSize = 1.2 }); list.Add("html", new HtmlGenerator()); list.Add("strong", new StrongGenerator()); list.Add("b", list["strong"]); list.Add("text", new TextGenerator()); list.Add("em", new EmGenerator()); list.Add("i", list["em"]); list.Add("a", new LinkGenerator()); list.Add("img", new CacheImageGenerator()); //list.Add("img", new ImageGenerator()); list.Add("ul", new UlGenerator()); list.Add("script", new EmptyGenerator()); return list; }
private void Animate(FrameworkElement element, double from, double to, TimeSpan duration, Action<FrameworkElement> completed) { AnimationTarget = element; TargetOpacity = to; AnimationCompleted = completed; if (_Storyboard == null) { Init(); } else { _Storyboard.Stop(); } /*time*/ _KeyFrame_to.KeyTime = KeyTime.FromTimeSpan(duration); /*value*/ _KeyFrame_from.Value = from; _KeyFrame_to.Value = to; Storyboard.SetTarget(_Animation, element); _Storyboard.Begin(); }
private void UserControl_DataContextChanged(FrameworkElement sender, DataContextChangedEventArgs args) { Graph.ClearSeries(); var item = DataContext as ChartSong; if (item == null) return; var color = Colors.White; switch (item.ChangeDirection) { case ChartSong.Direction.Up: color = Colors.Green; break; case ChartSong.Direction.Down: color = Colors.Red; break; } ChangePercentBlock.Foreground = new SolidColorBrush(color); var data = item.Signals.Select((p, i) => new Point(i, p)).ToList(); var serie = new Serie("Signals") {ShiftSize = 100}; serie.SetData(data); Graph.AutoRedraw = true; Graph.AddSerie(serie); }
internal static async Task Render(CompositionEngine compositionEngine, SharpDX.Direct2D1.RenderTarget renderTarget, FrameworkElement rootElement, Line line) { var rect = line.GetBoundingRect(rootElement).ToSharpDX(); //var fill = line.Fill.ToSharpDX(renderTarget, rect); var stroke = await line.Stroke.ToSharpDX(renderTarget, rect); if (stroke == null || line.StrokeThickness <= 0) { return; } //var layer = new Layer(renderTarget); //var layerParameters = new LayerParameters(); //layerParameters.ContentBounds = rect; //renderTarget.PushLayer(ref layerParameters, layer); renderTarget.DrawLine( new DrawingPointF( rect.Left + (float)line.X1, rect.Top + (float)line.Y1), new DrawingPointF( rect.Left + (float)line.X2, rect.Top + (float)line.Y2), stroke, (float)line.StrokeThickness, line.GetStrokeStyle(compositionEngine.D2DFactory)); //renderTarget.PopLayer(); }
public static Control FindNearestStatefulControl(FrameworkElement element) { if (element == null) { throw new ArgumentNullException("element"); } // Try to find an element which is the immediate child of a UserControl, ControlTemplate or other such "boundary" element FrameworkElement parent = element.Parent as FrameworkElement; // bubble up looking for a place to stop while (!VisualStateUtilities.HasVisualStateGroupsDefined(element) && VisualStateUtilities.ShouldContinueTreeWalk(parent)) { element = parent; parent = parent.Parent as FrameworkElement; } if (VisualStateUtilities.HasVisualStateGroupsDefined(element)) { // Once we've found such an element, use the VisualTreeHelper to get it's parent. For most elements the two are the // same, but for children of a ControlElement this will give the control that contains the template. Control templatedParent = VisualTreeHelper.GetParent(element) as Control; if (templatedParent != null) { return templatedParent; } else { return element as Control; } } return null; }
public void When_Child_Has_Fixed_Size_Smaller_than_Parent() { var parentSize = new Windows.Foundation.Size(100, 100); var childSize = new Windows.Foundation.Size(500, 500); var SUT = new Border() { Width = parentSize.Width, Height = parentSize.Height }; var child = new View() { Width = childSize.Width, Height = childSize.Height }; SUT.AddChild(child); SUT.Measure(new Windows.Foundation.Size(100, 100)); var measuredSize = SUT.DesiredSize; SUT.Arrange(new Windows.Foundation.Rect(0, 0, 100, 100)); Assert.AreEqual(parentSize, measuredSize); Assert.AreEqual(new Windows.Foundation.Rect(0, 0, parentSize.Width, parentSize.Height), child.Arranged); }
public void When_Child_Is_Not_Stretch_With_MinSize() { var parentSize = new Windows.Foundation.Size(500, 500); var minSize = new Windows.Foundation.Size(100, 100); var SUT = new Border() { Width = parentSize.Width, Height = parentSize.Height }; var child = new View() { MinWidth = minSize.Width, MinHeight = minSize.Height, HorizontalAlignment = HorizontalAlignment.Left, VerticalAlignment = VerticalAlignment.Top }; SUT.AddChild(child); SUT.Measure(new Windows.Foundation.Size(500, 500)); var measuredSize = SUT.DesiredSize; SUT.Arrange(new Windows.Foundation.Rect(0, 0, 500, 500)); Assert.AreEqual(parentSize, measuredSize); Assert.AreEqual(new Windows.Foundation.Rect(0, 0, minSize.Width, minSize.Height), child.Arranged); }
public void When_Grid_Has_Two_Columns_And_VerticalAlignment_Top() { var SUT = new Grid() { Name = "test" }; SUT.VerticalAlignment = VerticalAlignment.Top; SUT.ColumnDefinitions.Add(new ColumnDefinition { Width = "*" }); SUT.ColumnDefinitions.Add(new ColumnDefinition { Width = "*" }); var child = new View { Name = "Child01", RequestedDesiredSize = new Windows.Foundation.Size(10, 10) }; SUT.AddChild(child); SUT.Measure(new Windows.Foundation.Size(20, 20)); var measuredSize = SUT.DesiredSize; SUT.Arrange(new Windows.Foundation.Rect(0, 0, 20, 20)); var childArrangedSize = child.Arranged; Assert.AreEqual(new Windows.Foundation.Size(20, 10), measuredSize); Assert.AreEqual(new Windows.Foundation.Rect(0, 0, 10, 10), childArrangedSize); }
/// <summary> /// Decides whether the specified framework elements intersect within a canvas. /// </summary> /// <param name="first">The first framework element.</param> /// <param name="second">The second framework element.</param> /// <returns>True if the elements intersect. False otherwise.</returns> public static bool IntersectsWith(this FrameworkElement first, FrameworkElement second) { Rect p1 = first.Position(); Rect p2 = second.Position(); return (p1.Y + p1.Height < p2.Y) || (p1.Y > p2.Y + p2.Height) || (p1.X + p1.Width < p2.X) || (p1.X > p2.X + p2.Width); }
public static async Task<MemoryStream> RenderToPngStream(FrameworkElement fe) { using (var engine = new CompositionEngine()) { return await engine.RenderToPngStream(fe); } }
public void FormatCell(ICellHandler cell, sw.FrameworkElement element, swc.DataGridCell gridcell, object dataItem) { if (GridHandler != null) { GridHandler.FormatCell(this, cell, element, gridcell, dataItem); } }
private void RevertRequestedTheme(FrameworkElement fe) { if (fe.RequestedTheme == ElementTheme.Default) { //The FrameworkElement doesn't have a RequestedTheme set, //so we will need to ask to the Application what theme is using. if (Application.Current.RequestedTheme == ApplicationTheme.Dark) { fe.RequestedTheme = ElementTheme.Light; } else { fe.RequestedTheme = ElementTheme.Dark; } } else if (fe.RequestedTheme == ElementTheme.Dark) { fe.RequestedTheme = ElementTheme.Light; } else { fe.RequestedTheme = ElementTheme.Dark; } CurrentThemeTxtBlock.Text = "Current theme is " + fe.RequestedTheme.ToString() + "."; }
public void When_Child_Has_Fixed_Size_Smaller_than_Parent() { var parentSize = new Windows.Foundation.Size(100, 100); var childSize = new Windows.Foundation.Size(500, 500); var SUT = new Border() { Width = parentSize.Width, Height = parentSize.Height }; var child = new View() { Width = childSize.Width, Height = childSize.Height }; SUT.Child = child; SUT.Measure(new Windows.Foundation.Size(100, 100)); var measuredSize = SUT.DesiredSize; SUT.Arrange(new Windows.Foundation.Rect(0, 0, 100, 100)); Assert.AreEqual(parentSize, measuredSize, $"(parentSize:{parentSize}) != (measuredSize:{measuredSize})"); var expectedArrange = new Windows.Foundation.Rect(0, 0, parentSize.Width, parentSize.Height); var layoutSlot = LayoutInformation.GetLayoutSlot(child); Assert.AreEqual(expectedArrange, layoutSlot, $"(expectedArrange:{expectedArrange}) != (layoutSlot: {layoutSlot})"); }
protected override bool CommitCellEdit(sw.FrameworkElement editingElement) { var control = editingElement as swc.TextBox ?? editingElement.FindChild <swc.TextBox> ("control"); Handler.SetTextValue(control.DataContext, control.Text); return(true); }
internal static bool TrySetBorderThickness(this IFrameworkElement frameworkElement, Thickness borderThickness) { switch (frameworkElement) { case Grid g: g.BorderThickness = borderThickness; return true; case StackPanel sp: sp.BorderThickness = borderThickness; return true; case RelativePanel rp: rp.BorderThickness = borderThickness; return true; case Microsoft.UI.Xaml.Controls.LayoutPanel lp: lp.BorderThickness = borderThickness; return true; case Control c: c.BorderThickness = borderThickness; return true; case ContentPresenter cp: cp.BorderThickness = borderThickness; return true; case Border b: b.BorderThickness = borderThickness; return true; } return false; }
internal static bool TryGetCornerRadius(this IFrameworkElement frameworkElement, out CornerRadius cornerRadius) { switch (frameworkElement) { case Grid g: cornerRadius = g.CornerRadius; return(true); case StackPanel sp: cornerRadius = sp.CornerRadius; return(true); case Control c: cornerRadius = c.CornerRadius; return(true); case ContentPresenter cp: cornerRadius = cp.CornerRadius; return(true); case Border b: cornerRadius = b.CornerRadius; return(true); case Panel p: cornerRadius = p.CornerRadius; return(true); } cornerRadius = default; return(false); }
public void When_One_Child_With_Margin_5() { var SUT = new Grid() { Name = "test" }; var c1 = new View { Name = "Child01", Margin = new Thickness(5) } .GridPosition(0, 0); SUT.AddChild(c1); SUT.Measure(new Size(20, 20)); SUT.DesiredSize.Should().Be(new Size(10, 10)); SUT.UnclippedDesiredSize.Should().Be(new Size(10, 10)); c1.DesiredSize.Should().Be(new Size(10, 10)); c1.UnclippedDesiredSize.Should().Be(new Size(0, 0)); // UnclippedDesiredSize excludes margins SUT.Arrange(new Rect(0, 0, 20, 20)); SUT.Arranged.Should().Be((Rect)"0,0,20,20"); SUT.ClippedFrame.Should().Be((Rect)"0,0,20,20"); c1.Arranged.Should().Be((Rect)"5,5,10,10"); c1.ClippedFrame.Should().Be((Rect)"0,0,10,10"); SUT.GetChildren().Should().HaveCount(1); }
public void When_Child_Is_Stretch_With_MaxSize() { var parentSize = new Windows.Foundation.Size(500, 500); var maxSize = new Windows.Foundation.Size(100, 100); var SUT = new Border() { Width = parentSize.Width, Height = parentSize.Height }; var child = new View() { MaxWidth = maxSize.Width, MaxHeight = maxSize.Height }; SUT.AddChild(child); SUT.Measure(new Windows.Foundation.Size(500, 500)); var measuredSize = SUT.DesiredSize; SUT.Arrange(new Windows.Foundation.Rect(0, 0, 500, 500)); Assert.AreEqual(parentSize, measuredSize); Assert.AreEqual(new Windows.Foundation.Rect((SUT.Width - maxSize.Width) / 2, (SUT.Height - maxSize.Height) / 2, maxSize.Width, maxSize.Height), child.Arranged); }
public void When_One_Child_With_Margin_1234_Size8() { using var _ = new AssertionScope(); var SUT = new Grid { Name = "test", Padding = new Thickness(2) }; var c1 = new View { Name = "Child01", Margin = new Thickness(1, 2, 3, 4) } .GridPosition(0, 0); SUT.AddChild(c1); SUT.Measure(new Size(8, 8)); SUT.DesiredSize.Should().Be(new Size(8, 8)); SUT.UnclippedDesiredSize.Should().Be(new Size(8, 10)); c1.DesiredSize.Should().Be(new Size(4, 6)); c1.UnclippedDesiredSize.Should().Be(new Size(0, 0)); // UnclippedDesiredSize excludes margins SUT.Arrange(new Rect(0, 0, 8, 8)); SUT.Arranged.Should().Be((Rect)"0,0,8,8"); SUT.ClippedFrame.Should().Be((Rect)"0,0,8,8"); c1.Arranged.Should().Be((Rect)"3,4,0,0"); c1.ClippedFrame.Should().Be((Rect)"0,0,0,0"); SUT.GetChildren().Should().HaveCount(1); }
// Unforrunately actual width property binding doesn't work atm. There is a workaround via SizeChanged event private void SetDayElementsWidth(FrameworkElement x) { _currentDayElementWidth = x.ActualWidth/7; CalendarDays.OfType<IList<CalendarDayInfo>>() .SelectMany(y => y) .ForEach(y => y.ElementWidth = _currentDayElementWidth); }
internal static bool TryGetPadding(this IFrameworkElement frameworkElement, out Thickness padding) { switch (frameworkElement) { case Grid g: padding = g.Padding; return(true); case StackPanel sp: padding = sp.Padding; return(true); case Control c: padding = c.Padding; return(true); case ContentPresenter cp: padding = cp.Padding; return(true); case Border b: padding = b.Padding; return(true); case Panel p: padding = p.Padding; return(true); } padding = default; return(false); }
static public void AnimateOpacity(FrameworkElement element, double start, double end, double duration) { element.Opacity = 0; Duration animationDuration = new Duration(TimeSpan.FromSeconds(duration)); DoubleAnimation opacityAnimation = new DoubleAnimation(); opacityAnimation.Duration = animationDuration; opacityAnimation.From = start; opacityAnimation.To = end; Storyboard sb = new Storyboard(); sb.Duration = animationDuration; sb.Children.Add(opacityAnimation); Storyboard.SetTarget(opacityAnimation, element); // Set the X and Y properties of the Transform to be the target properties // of the two respective DoubleAnimations. Storyboard.SetTargetProperty(opacityAnimation, "Opacity"); // Begin the animation. sb.Begin(); }
internal static bool TrySetPadding(this IFrameworkElement frameworkElement, Thickness padding) { switch (frameworkElement) { case Grid g: g.Padding = padding; return(true); case StackPanel sp: sp.Padding = padding; return(true); case Control c: c.Padding = padding; return(true); case ContentPresenter cp: cp.Padding = padding; return(true); case Border b: b.Padding = padding; return(true); case Panel p: p.Padding = padding; return(true); } return(false); }
// If showPicker == false => PicturesLibrary capability must be set in client app public static async Task<IStorageFile> CreateBitmapFromElement(FrameworkElement uielement, bool showPicker = true, string filenamePrefix = "receipt") { try { var renderTargetBitmap = new RenderTargetBitmap(); await renderTargetBitmap.RenderAsync(uielement); var file = await SaveFile(showPicker, filenamePrefix); var pixelBuffer = await renderTargetBitmap.GetPixelsAsync(); using (var stream = await file.OpenAsync(FileAccessMode.ReadWrite)) { var logicalDpi = DisplayInformation.GetForCurrentView().LogicalDpi; var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, stream); encoder.SetPixelData( BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint) renderTargetBitmap.PixelWidth, (uint) renderTargetBitmap.PixelHeight, logicalDpi, logicalDpi, pixelBuffer.ToArray()); await encoder.FlushAsync(); } return file; } catch (Exception ex) { Debug.WriteLine(ex); return null; } }
internal static bool TryGetBorderThickness(this IFrameworkElement frameworkElement, out Thickness borderThickness) { switch (frameworkElement) { case Grid g: borderThickness = g.BorderThickness; return(true); case StackPanel sp: borderThickness = sp.BorderThickness; return(true); case Control c: borderThickness = c.BorderThickness; return(true); case ContentPresenter cp: borderThickness = cp.BorderThickness; return(true); case Border b: borderThickness = b.BorderThickness; return(true); case Panel p: borderThickness = p.BorderThickness; return(true); } borderThickness = default; return(false); }
//Do not use the below extension as it is slower than the one that follows //public static async Task Render(this WriteableBitmap wb, FrameworkElement fe) //{ // var ms = await RenderToPngStream(fe); // using (var msrandom = new MemoryRandomAccessStream(ms)) // { // await wb.SetSourceAsync(msrandom); // } //} public static async Task<WriteableBitmap> Render(FrameworkElement fe) { using (var engine = new CompositionEngine()) { return await engine.RenderToWriteableBitmap(fe); } }
internal static bool TrySetBorderThickness(this IFrameworkElement frameworkElement, Thickness borderThickness) { switch (frameworkElement) { case Grid g: g.BorderThickness = borderThickness; return(true); case StackPanel sp: sp.BorderThickness = borderThickness; return(true); case Control c: c.BorderThickness = borderThickness; return(true); case ContentPresenter cp: cp.BorderThickness = borderThickness; return(true); case Border b: b.BorderThickness = borderThickness; return(true); case Panel p: p.BorderThickness = borderThickness; return(true); } return(false); }
/// <summary> /// Goes to specified visual state, waiting for the transition to complete. /// </summary> /// <param name="control"> /// Control to transition. /// </param> /// <param name="visualStatesHost"> /// FrameworkElement that defines the visual states /// (usually the root of the control's template). /// </param> /// <param name="stateGroupName"> /// Name of the state group /// (speeds up the search for the state transition storyboard). /// </param> /// <param name="stateName"> /// State to transition to. /// </param> /// <returns> /// Awaitable task that completes when the transition storyboard completes. /// </returns> /// <remarks> /// If a state transition storyboard is not found - the task /// completes immediately. /// </remarks> public static async Task GoToVisualStateAsync( this Control control, FrameworkElement visualStatesHost, string stateGroupName, string stateName) { var tcs = new TaskCompletionSource<Storyboard>(); Storyboard storyboard = GetStoryboardForVisualState(visualStatesHost, stateGroupName, stateName); if (storyboard != null) { EventHandler<object> eh = null; eh = (s, e) => { storyboard.Completed -= eh; tcs.SetResult(storyboard); }; storyboard.Completed += eh; } VisualStateManager.GoToState(control, stateName, true); if (storyboard == null) { return; } await tcs.Task; }
private void ConsoleGainFocus(FrameworkElement grid) { ShowBackgroundImage(((Console)grid.DataContext).BackgroundLink); ConsoleFocus.Stop(); Storyboard.SetTarget(ConsoleFocus, grid); ConsoleFocus.Begin(); }
/// <summary> /// Returns true if the element is contained in a popup. /// </summary> public static bool IsInPopup(FrameworkElement element) { if (element is Popup) return true; return GetParentPopup(element) != null; }
public static T GetFirstDescendantOfType <T>(this Windows.UI.Xaml.FrameworkElement parent) where T : class { Queue <Windows.UI.Xaml.FrameworkElement> elementQueue = new Queue <Windows.UI.Xaml.FrameworkElement>(); elementQueue.Enqueue(parent); while (elementQueue.Count > 0) { var element = elementQueue.Dequeue(); if (element is T) { return(element as T); } for (int i = 0; i < VisualTreeHelper.GetChildrenCount(element); i++) { var child = VisualTreeHelper.GetChild(element, i); var t = child as T; if (t != null) { return(t); } elementQueue.Enqueue((Windows.UI.Xaml.FrameworkElement)child); } } return(null); }
private void OnDataContextChanged(FrameworkElement sender, DataContextChangedEventArgs args) { if (DataContext == null) return; ViewModel.AnimeItemDisplayContext = DisplayContext; Bindings.Update(); }
/// <summary>Construct Get Image Samples sample control</summary> public GetSamples() { InitializeComponent(); _graphicsOverlay = MyMapView.GraphicsOverlays.First(); _mapTip = MyMapView.Overlays.Items.First() as FrameworkElement; MyMapView.LayerLoaded += MyMapView_LayerLoaded; }
private static object AutomationInvokeAction(FrameworkElement element) { var invokeProvider = element.GetProvider<IInvokeProvider>(PatternInterface.Invoke); invokeProvider.Invoke(); return null; }
public ManipulationManager(Windows.UI.Xaml.FrameworkElement element, Windows.UI.Xaml.Controls.Canvas parent) : base(element, parent) { _handlersRegistered = false; InitialTransform = _target.RenderTransform; ResetManipulation(); }
protected override void OnApplyTemplate() { base.OnApplyTemplate(); ContentPresenter = (ContentControl)GetTemplateChild("ContentPresenter"); planeProjection = (PlaneProjection)GetTemplateChild("Rotator"); LayoutRoot = (FrameworkElement)GetTemplateChild("LayoutRoot"); Animation = (Storyboard)GetTemplateChild("Animation"); Animation.Completed += Animation_Completed; rotationKeyFrame = (EasingDoubleKeyFrame)GetTemplateChild("rotationKeyFrame"); offestZKeyFrame = (EasingDoubleKeyFrame)GetTemplateChild("offestZKeyFrame"); scaleXKeyFrame = (EasingDoubleKeyFrame)GetTemplateChild("scaleXKeyFrame"); scaleYKeyFrame = (EasingDoubleKeyFrame)GetTemplateChild("scaleYKeyFrame"); scaleTransform = (ScaleTransform)GetTemplateChild("scaleTransform"); planeProjection.RotationY = yRotation; planeProjection.LocalOffsetZ = zOffset; if (ContentPresenter != null) { ContentPresenter.Tapped += ContentPresenter_Tapped; } if (Animation != null) { xAnimation = new DoubleAnimation(); Animation.Children.Add(xAnimation); Storyboard.SetTarget(xAnimation, this); Storyboard.SetTargetProperty(xAnimation, "(Canvas.Left)"); } }
public override void SetContainerContent(sw.FrameworkElement content) { content.HorizontalAlignment = sw.HorizontalAlignment.Left; content.VerticalAlignment = sw.VerticalAlignment.Top; content.SizeChanged += (s, e) => UpdateSizes(); scroller.Content = content; }
public virtual void FormatCell(IGridColumnHandler column, ICellHandler cell, sw.FrameworkElement element, swc.DataGridCell gridcell, object dataItem) { if (IsEventHandled(Grid.CellFormattingEvent)) { var row = Control.Items.IndexOf(dataItem); Widget.OnCellFormatting(new FormatEventArgs(column.Widget as GridColumn, gridcell, dataItem, row, element)); } }
public override sw.FrameworkElement SetupCell(IGridColumnHandler column, sw.FrameworkElement defaultContent) { if (object.ReferenceEquals(column, Columns.Collection[0].Handler)) { return(TreeToggleButton.Create(defaultContent, controller)); } return(defaultContent); }
public static bool FireDoubleTapped(Windows.UI.Xaml.FrameworkElement element, Windows.UI.Xaml.Input.DoubleTappedRoutedEventArgs e, int numberOfTaps, Listener listener) { var args = new UwpTapEventArgs(element, e, numberOfTaps); args.Listener = listener; listener.OnDoubleTapped(args); e.Handled = args.Handled; return(e.Handled); }
public UwpTapEventArgs(Windows.UI.Xaml.FrameworkElement element, Windows.UI.Xaml.Input.TappedRoutedEventArgs args, int numberOfTaps) { ElementPosition = element.GetXfViewFrame(); var point = args.GetPosition(element); ElementTouches = new Xamarin.Forms.Point[] { point.ToXfPoint() }; WindowTouches = new Xamarin.Forms.Point[] { element.PointInNativeAppWindowCoord(point).ToXfPoint() }; NumberOfTaps = numberOfTaps; }
public override void Remove(sw.FrameworkElement child) { if (border.Child == child) { content = null; border.Child = null; UpdatePreferredSize(); } }
sw.FrameworkElement SetupCell(sw.FrameworkElement element) { var container = new swc.StackPanel { Orientation = swc.Orientation.Horizontal }; container.Children.Add(Image()); container.Children.Add(element); return(Handler.SetupCell(container)); }