internal void AddAdorner( AdornerLayer treeViewAdornerLayer, FrameworkElement adornedElement, ExplorerEFElement explorerElement, ExplorerFrame explorerFrame) { var adornerY = GetAdornerY(adornedElement, explorerElement, explorerFrame); if (adornerY >= 0) { SearchTickAdorner adorner; if (!_adorners.TryGetValue(adornerY, out adorner)) { adorner = new SearchTickAdorner(adornerY, adornedElement); _adorners[adornerY] = adorner; treeViewAdornerLayer.Add(adorner); // adding adorners in batches of 100 - see bug: Windows OS Bugs 1750717 if ((_adorners.Count % 100) == 0) { treeViewAdornerLayer.UpdateLayout(); } } adorner.AddExplorerElement(explorerElement); } }
public static Border CreateBlockBox(FrameworkElement child, double width, double height, double x, double y, Color backgroundColor) { var border = new Border() { BorderThickness = new Thickness(1, 1, 1, 1), BorderBrush = Brushes.Silver, Background = new SolidColorBrush(backgroundColor), Width = width, Height = height, Margin = new Thickness(x, y, 0, 0), Child = child }; border.MouseEnter += (s, e) => { border.Width = Math.Max(width, child.ActualWidth); border.Height = Math.Max(height, child.ActualHeight); Panel parent = (Panel)border.Parent; border.TopMost(); }; border.MouseLeave += (s, e) => { border.Width = width; border.Height = height; }; return border; }
public void ShowChildWindow(FrameworkElement content) { XmlContent = content; OnPropertyChanged("XmlContent"); WindowVisibility = Visibility.Visible; OnPropertyChanged("WindowVisibility"); }
public UIAdorner(FrameworkElement adornee, FrameworkElement content) : base(adornee) { this.adornee = adornee; this.content = content; AddVisualChild(this.content); }
protected override FrameworkElement ModifyNewContent(ITransitionControl container, FrameworkElement newContent) { if (newContent == null) { HideBackground(container); container.Remove(_border); return null; } ShowBackground(container); _border = WrapInBorder(newContent); _border.Opacity = 0; SetPosition(_border); newContent.SizeChanged += (sender, e) => SetPosition(_border); var ctrl = container.AsControl(); ctrl.SizeChanged += (sender, e) => SetPosition(_border); return _border; }
public void SetupTargetBinding(FrameworkElement targetObject) { if (targetObject == null) { return; } // Prevent the designer from reporting exceptions since // changes will be made of a Binding in use if it is set if (DesignerProperties.GetIsInDesignMode(this) == true) return; // Bind to the selected TargetProperty, e.g. ActualHeight and get // notified about changes in OnTargetPropertyListenerChanged var listenerBinding = new Binding { Source = targetObject, Path = new PropertyPath(TargetProperty), Mode = BindingMode.OneWay }; BindingOperations.SetBinding(this, TargetPropertyListenerProperty, listenerBinding); // Set up a OneWayToSource Binding with the Binding declared in Xaml from // the Mirror property of this class. The mirror property will be updated // everytime the Listener property gets updated BindingOperations.SetBinding(this, TargetPropertyMirrorProperty, Binding); TargetPropertyValueChanged(); }
public void Detach(FrameworkElement element) { element.MouseMove -= MouseMoveHandler; element.MouseRightButtonDown -= MouseDownHandler; element.MouseRightButtonUp -= MouseUpHandler; element.MouseWheel -= OnMouseWheel; }
public static bool StateWellDefined(FrameworkElement element, string stateName, bool prefixControlName = false) { string state = string.IsNullOrWhiteSpace(stateName) ? null : (prefixControlName ? element.Name + "_" + stateName : stateName); // Look for the visual state on the first child object. This is generally where states are declared // when they are part of a ControlTemplate. FrameworkElement child = null; if (VisualTreeHelper.GetChildrenCount(element) > 0) child = VisualTreeHelper.GetChild(element, 0) as FrameworkElement; if (child == null) return false; var vsgs = VisualStateManager.GetVisualStateGroups(child); if (vsgs != null && vsgs.Count > 0) { foreach (VisualStateGroup vsg in vsgs) { if (vsg.States != null) { foreach (VisualState vs in vsg.States) { if (vs.Name == state) return true; } } } } return false; }
public static void SetUpdateBindingOnChange(FrameworkElement element, bool value) { Action<TextBox, bool> action = (txtBox, updateValue) => { if (GetUpdateBindingOnChange(txtBox) == updateValue) return; if (updateValue) { txtBox.TextChanged += element_TextChanged; } else { txtBox.TextChanged -= element_TextChanged; } txtBox.SetValue(UpdateBindingOnChangeProperty, updateValue); }; Deployment.Current.Dispatcher.BeginInvoke(() => { if (element is TextBox) { action.Invoke(element as TextBox, value); return; } element.GetChildrens<TextBox>().ForEach(i => action.Invoke(i, value)); }); }
public void OnLoaded(object sender, EventArgs e) { // Enable moving the window when clicking on the control CtlMoveable this.CtlMoveable = (FrameworkElement)this.Template.FindName("CtlMoveable", this); if (null != this.CtlMoveable) { this.CtlMoveable.MouseLeftButtonDown += new MouseButtonEventHandler(OnMoveableClick); } Application.Current.MainWindow = this; // Disable Minimize and close buttons var BtnClose = (FrameworkElement)this.Template.FindName("BtnClose", this); if (BtnClose != null) BtnClose.Visibility = System.Windows.Visibility.Hidden; var BtnMinimize = (FrameworkElement)this.Template.FindName("BtnMinimize", this); if (BtnMinimize != null) BtnMinimize.Visibility = System.Windows.Visibility.Hidden; // Check for updates async // and register an event to catch its answer vm.LoadApplicationData(); vm.SelfUpdaterApp.PropertyChanged += vm_PropertyChanged; vm.UpdateSelfUpdaterAsync(); CtlProgress.Maximum = 1; }
public void CloseExists() { CreateContainerWithRealMessageBus(); var title = Guid.NewGuid().ToString(); var viewModel = Substitute.For<ITitledViewModel>(); viewModel.Title.Returns(title); var view = new FrameworkElement(); view.DataContext = viewModel; var viewTarget = ViewTargets.DefaultView; var viewResult = new ViewResult(view, viewTarget); var viewBuilder = Substitute.For<IViewFactory>(); viewBuilder.Build(Arg.Any<ViewTargets>(), Arg.Any<Object>()) .Returns(viewResult); ComponentContainer.Container.Register(Component.For<IViewFactory>().Instance(viewBuilder)); var window = new Window(); var tabControl = new TabControl(); var viewController = new ViewPlacer(window, tabControl); var newTabItem = new TabItem() { Header = title }; tabControl.Items.Add(newTabItem); var message = new CloseViewMessage(title); _MessageBus.Publish<CloseViewMessage>(message); Assert.AreEqual(0, tabControl.Items.Count); }
/// <summary> /// Return wheter the mouse is over a control /// </summary> /// <param name="s"></param> /// <param name="e"></param> /// <returns>True if the mouse is over a control, false otherwise</returns> internal static bool IsMouseOver(FrameworkElement s, System.Windows.Input.MouseEventArgs e) { Rect bounds = new Rect(0, 0, s.ActualWidth, s.ActualHeight); if (bounds.Contains(e.GetPosition(s))) return true; return false; }
private void MakeDataContextAware(FrameworkElement frameworkElement) { Contract.Requires<ArgumentNullException>(frameworkElement != null); if (frameworkElement.DataContext != null) MakeAware(frameworkElement.DataContext); }
public override void BindCellContent(System.Windows.FrameworkElement cellContent, C1.WPF.DataGrid.DataGridRow row) { var maskedTextBox = (C1MaskedTextBox)cellContent; if (Binding == null) { maskedTextBox.ClearValue(C1MaskedTextBox.ValueProperty); return; } maskedTextBox.Mask = Mask; maskedTextBox.TextMaskFormat = TextMaskFormat; maskedTextBox.PromptChar = ' '; maskedTextBox.TextWrapping = TextWrapping; maskedTextBox.HorizontalAlignment = base.HorizontalAlignment; maskedTextBox.VerticalAlignment = base.VerticalAlignment; maskedTextBox.BorderBrush = null; maskedTextBox.Background = Brushes.Transparent; if (FlowDirection != null) { maskedTextBox.FlowDirection = (FlowDirection)FlowDirection; } if (Binding != null) { Binding newBinding = CopyBinding(Binding); newBinding.Source = row.DataItem; newBinding.Mode = BindingMode.OneWay; maskedTextBox.SetBinding(C1MaskedTextBox.ValueProperty, newBinding); } }
private void xEnumVisuals(System.Windows.FrameworkElement root) { Stack <System.Windows.FrameworkElement> children = new Stack <System.Windows.FrameworkElement>(); children.Push(root); while (children.Count > 0) { System.Windows.FrameworkElement child = children.Pop(); child.Tag = this; if (child is ContentControl) { System.Windows.FrameworkElement contentElement = ((ContentControl)child).Content as System.Windows.FrameworkElement; if (contentElement != null) { children.Push(contentElement); } continue; } if (child is Panel) { Panel panelElement = child as Panel; foreach (System.Windows.FrameworkElement panelChild in panelElement.Children) { children.Push(panelChild); } } } }
public override void SetContainerContent(sw.FrameworkElement content) { this.content.Children.Add(dockMain); swc.DockPanel.SetDock(gridButtons, swc.Dock.Bottom); dockMain.Children.Add(gridButtons); dockMain.Children.Add(content); }
protected override bool CommitCellEdit(System.Windows.FrameworkElement editingElement) { DatePicker dp = editingElement as DatePicker; if (dp == null) { return(true); } dp.Text = "01/01/2001"; //if (!isCellValueChanged) tb.Text = Convert.ToString(previouseCellValue); //if (MaxScale > 0 && FormatCellAfterCellEndEdit) //{ // if (Convert.ToString(tb.Text).Trim().Length == 0) tb.Text = "0"; // string decimalFormat = "0." + "".PadLeft(MaxScale, '0'); // tb.Text = Convert.ToDecimal(Convert.ToString(tb.Text)).ToString(decimalFormat); //} BindingExpression binding = editingElement.GetBindingExpression(DatePicker.TextProperty); if (binding != null) { binding.UpdateSource(); } return(true); //base.CommitCellEdit(editingElement); }
void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) { switch (connectionId) { case 1: this.LogEventsGrid = ((System.Windows.Controls.Grid)(target)); return; case 2: this.LogEventsGridColumn1 = ((System.Windows.FrameworkElement)(target)); return; case 3: this.LogEventsGridColumn2 = ((System.Windows.FrameworkElement)(target)); return; case 4: this.LogEventsGridColumn3 = ((System.Windows.FrameworkElement)(target)); return; case 5: #line 132 "..\..\..\Views\MainWindow.xaml" ((System.Windows.Controls.Button)(target)).Click += new System.Windows.RoutedEventHandler(this.Button_Click); #line default #line hidden return; } this._contentLoaded = true; }
public override void BindCellContent(System.Windows.FrameworkElement cellContent, C1.WPF.DataGrid.DataGridRow row) { Button button = (Button)cellContent; button.HorizontalAlignment = base.HorizontalAlignment; button.VerticalAlignment = base.VerticalAlignment; button.Margin = new Thickness(4, 4, 4, 4); if (FlowDirection != null) { button.FlowDirection = (FlowDirection)FlowDirection; } if (!string.IsNullOrEmpty(Text)) { button.DataContext = new { Text = this.Text } } ; Binding bindCommand = new Binding("Command") { Source = this }; Binding bindCommandParameter = new Binding("DataItem") { Source = row }; button.SetBinding(Button.CommandProperty, bindCommand); button.SetBinding(Button.CommandParameterProperty, bindCommandParameter); button.Template = buttonTemplate; }
void SetMargins(sw.FrameworkElement c, int x, int y) { var margin = new sw.Thickness(); if (x > 0) { margin.Left = spacing.Width / 2; } if (x < Control.ColumnDefinitions.Count - 1) { margin.Right = spacing.Width / 2; } if (y > 0) { margin.Top = spacing.Height / 2; } if (y < Control.RowDefinitions.Count - 1) { margin.Bottom = spacing.Height / 2; } c.HorizontalAlignment = sw.HorizontalAlignment.Stretch; c.VerticalAlignment = sw.VerticalAlignment.Stretch; c.Margin = margin; }
public override void DropElement(System.Windows.FrameworkElement element, LayoutItemInsertionPoint insertionPoint, LayoutItemInsertionKind insertionKind) { MyLayoutGroup elemPar = element.Parent as MyLayoutGroup; bool IsSourceIsolated = false; if (elemPar != null) { IsSourceIsolated = elemPar.IsIsolatedGroup; } bool IsTargetIsolated = false; MyLayoutGroup targParent = insertionPoint.Element.Parent as MyLayoutGroup; if (targParent != null) { IsTargetIsolated = targParent.IsIsolatedGroup; } if (element.Parent != null) { if (element.Parent != insertionPoint.Element.Parent && (IsSourceIsolated || IsTargetIsolated)) { return; } } if (element.Parent == null && IsTargetIsolated) { return; } base.DropElement(element, insertionPoint, insertionKind); }
public void SaveToTIF(string fileName) { XpsDocument xd = new XpsDocument(fileName, System.IO.FileAccess.Read); FixedDocumentSequence fds = xd.GetFixedDocumentSequence(); DocumentPaginator paginator = fds.DocumentPaginator; System.Windows.Media.Visual visual = paginator.GetPage(0).Visual; System.Windows.FrameworkElement fe = (System.Windows.FrameworkElement)visual; int multiplyFactor = 4; string outputPath = fileName.Replace(".xps", ".tif"); RenderTargetBitmap bmp = new RenderTargetBitmap( (int)fe.ActualWidth * multiplyFactor, (int)fe.ActualHeight * multiplyFactor, 96d * multiplyFactor, 96d * multiplyFactor, System.Windows.Media.PixelFormats.Default); bmp.Render(fe); TiffBitmapEncoder tff = new TiffBitmapEncoder(); tff.Frames.Add(BitmapFrame.Create(bmp)); using (Stream stream = File.Create(outputPath)) { tff.Save(stream); } }
public void CloseChildWindow() { WindowVisibility = Visibility.Collapsed; OnPropertyChanged("WindowVisibility"); XmlContent = null; OnPropertyChanged("XmlContent"); }
public static IEnumerable <System.Windows.FrameworkElement> SelfAndAncestors(this System.Windows.FrameworkElement element) { for (; element != null; element = (element.TemplatedParent ?? element.Parent) as System.Windows.FrameworkElement) { yield return(element); } }
public static void ApplyAllTemplates(this sw.FrameworkElement parent) { if (parent == null) { return; } parent.ApplyTemplate(); foreach (var logicalChild in sw.LogicalTreeHelper.GetChildren(parent)) { if (logicalChild is sw.FrameworkElement childElement) { // recursively apply childElement.ApplyAllTemplates(); } } int childrenCount = swm.VisualTreeHelper.GetChildrenCount(parent); for (int i = 0; i < childrenCount; i++) { var child = swm.VisualTreeHelper.GetChild(parent, i); // If the child is not of the request child type child if (child is sw.FrameworkElement childElement) { // recursively apply childElement.ApplyAllTemplates(); } } }
public DragObject Initialize(FrameworkElement target) { this.target = target; InitializeBound(); return(this); }
public override bool TryInvoke(System.Windows.FrameworkElement owner, AutomationMethod method, out AutomationValue result) { result = AutomationValue.NotSetValue; if (owner is not TestHost testHost) { return(false); } var itemsControl = testHost.FindVisualDescendantByType <System.Windows.Controls.ItemsControl>(); if (itemsControl is null) { return(false); } itemsControl.ItemsPanel = new ItemsPanelTemplate(new FrameworkElementFactory(typeof(StaggeredPanel))); var dataTemplate = new DataTemplate(typeof(StaggeredPanelTestItem)); var textBlock = new FrameworkElementFactory(typeof(TextBlock)); //textBlock.SetBinding(TextBlock.WidthProperty, new Binding(nameof(StaggeredPanelTestItem.Width))); //textBlock.SetBinding(TextBlock.HeightProperty, new Binding(nameof(StaggeredPanelTestItem.Height))); textBlock.SetBinding(TextBlock.TextProperty, new Binding(nameof(StaggeredPanelTestItem.Content))); dataTemplate.VisualTree = textBlock; itemsControl.ItemTemplate = dataTemplate; result = AutomationValue.FromValue(true); return(true); }
void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) { switch (connectionId) { case 1: this.uncheckAllButton = ((System.Windows.Controls.Button)(target)); #line 32 "..\..\..\..\Views\AccessObjects\AccessPointsView.xaml" this.uncheckAllButton.Click += new System.Windows.RoutedEventHandler(this.uncheckAllButton_Click); #line default #line hidden return; case 2: this.showOnlyCheckedButton = ((System.Windows.Controls.Primitives.ToggleButton)(target)); #line 50 "..\..\..\..\Views\AccessObjects\AccessPointsView.xaml" this.showOnlyCheckedButton.Click += new System.Windows.RoutedEventHandler(this.showOnlyCheckedButton_Click); #line default #line hidden return; case 3: this.dummyElement = ((System.Windows.FrameworkElement)(target)); return; case 4: this.dgAccessPoints = ((System.Windows.Controls.DataGrid)(target)); return; } this._contentLoaded = true; }
public static void Bind(FrameworkElement view, object viewModel) { Log.Info($"Binding '{view}' to '{viewModel}'"); var namedElements = UIHelper.FindNamedChildren(view); var viewModelProperties = viewModel.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance); var matches = namedElements.Join(viewModelProperties, e => e.Name, p => p.Name, (e, p) => new { e, p }); foreach (var element in namedElements) { var matchingProperty = viewModelProperties.Where(p => p.Name == element.Name).SingleOrDefault(); if (matchingProperty == null) { Log.Debug($"No matching property for element '{element.Name}'"); continue; } if (!TryBind(element, matchingProperty, viewModel)) Log.Debug($"Could not bind element '{element.Name}' to property '{matchingProperty.Name}'"); } view.DataContext = viewModel; var viewAware = viewModel as IViewAware; viewAware?.AttachView(view); }
protected override bool CommitCellEdit(sw.FrameworkElement editingElement) { var control = editingElement as swc.ComboBox ?? editingElement.FindChild <swc.ComboBox> ("control"); Handler.SetValue(control.DataContext, control.SelectedValue); return(true); }
public void Attach(FrameworkElement element) { element.MouseMove += MouseMoveHandler; element.MouseRightButtonDown += MouseDownHandler; element.MouseRightButtonUp += MouseUpHandler; element.MouseWheel += OnMouseWheel; }
public override bool TryInvoke(FrameworkElement owner, AutomationMethod method, out AutomationValue result) { result = AutomationValue.NotSetValue; var pinnableToolTip = new PinnableToolTip { Name = "PinnableToolTipId", AllowCloseByUser = true, ResizeMode = ResizeMode.CanResize, MinWidth = 100, MinHeight = 100, HorizontalOffset = -12, VerticalOffset = -12, }; var dataTemplate = new DataTemplate(); var label = new FrameworkElementFactory(typeof(Label)); label.SetValue(ContentControl.ContentProperty, "Test content"); dataTemplate.VisualTree = label; pinnableToolTip.ContentTemplate = dataTemplate; owner.SetCurrentValue(PinnableToolTipService.ToolTipProperty, pinnableToolTip); result = AutomationValue.FromValue(true); return(true); }
public void Open(FrameworkElement container) { if (container != null) { _container = container; // 通过禁用来模拟模态的对话框 _container.IsEnabled = false; // 保持总在最上 this.Owner = GetOwnerWindow(container); if (this.Owner != null) { this.Owner.Closing += new System.ComponentModel.CancelEventHandler(Owner_Closing); } // 通过监听容器的Loaded和Unloaded来显示/隐藏窗口 _container.Loaded += new RoutedEventHandler(Container_Loaded); _container.Unloaded += new RoutedEventHandler(Container_Unloaded); } this.Show(); try { ComponentDispatcher.PushModal(); _dispatcherFrame = new DispatcherFrame(true); Dispatcher.PushFrame(_dispatcherFrame); } finally { ComponentDispatcher.PopModal(); } }
public static void SetSelectAllOnFocus(FrameworkElement element, bool value) { Action<TextBox, bool> action = (textBox, value1) => { if (GetSelectAllOnFocus(textBox) == value1) return; if (value1) { textBox.GotFocus += element_GotFocus; } else { textBox.GotFocus -= element_GotFocus; } textBox.SetValue(SelectAllOnFocusProperty, value1); }; Deployment.Current.Dispatcher.BeginInvoke(() => { if (element is TextBox) { action.Invoke(element as TextBox, value); } else { element.GetChildrens<TextBox>().ForEach(i => action.Invoke(i, value)); } }); }
public override void SetContainerContent(sw.FrameworkElement content) { content.HorizontalAlignment = sw.HorizontalAlignment.Left; content.VerticalAlignment = sw.VerticalAlignment.Top; content.SizeChanged += HandleSizeChanged; scroller.Content = content; }
/// <summary> /// Instantiates a new instance of this class. /// </summary> /// <param name="column">The column of the cell that is about to exit edit mode.</param> /// <param name="row">The row container of the cell container that is about to exit edit mode.</param> /// <param name="editingElement">The editing element within the cell.</param> /// <param name="editingUnit">The editing unit that is about to leave edit mode.</param> public DataGridCellEditEndingEventArgs(DataGridColumn column, DataGridRow row, FrameworkElement editingElement, DataGridEditAction editAction) { _dataGridColumn = column; _dataGridRow = row; _editingElement = editingElement; _editAction = editAction; }
public void Show(FrameworkElement popupContent) { _PopupContent = popupContent; _Popup = new Popup(); _Popup.Child = this; _Popup.IsOpen = true; }
public void FormatCell(ICellHandler cell, sw.FrameworkElement element, swc.DataGridCell gridcell, object dataItem) { if (GridHandler != null) { GridHandler.FormatCell(this, cell, element, gridcell, dataItem); } }
public MouseWheelSupport(FrameworkElement elementToAddMouseWheelSupportTo, FrameworkElement parentElementWithMouseWheelSupport) { ElementToAddMouseWheelSupportTo = elementToAddMouseWheelSupportTo; //Make sure the browser listener is setup if (browserListener == null) browserListener = new BrowserMouseWheelEventListener(); //Add an event handler to the browser listener for this particular Silverlight element browserListener.Moved += this.HandleBrowserMouseWheelMoved; //Setup the focus/blur handlers for the Silverlight element elementToAddMouseWheelSupportTo.GotFocus += new RoutedEventHandler(ElementGotFocus); elementToAddMouseWheelSupportTo.LostFocus += new RoutedEventHandler(ElementLostFocus); //Setup mouse move for the Silverlight element elementToAddMouseWheelSupportTo.MouseMove += new System.Windows.Input.MouseEventHandler(ElementMouseMove); elementToAddMouseWheelSupportTo.MouseEnter += new System.Windows.Input.MouseEventHandler(elementToAddMouseWheelSupportTo_MouseEnter); elementToAddMouseWheelSupportTo.MouseLeave += new System.Windows.Input.MouseEventHandler(elementToAddMouseWheelSupportTo_MouseLeave); elementToAddMouseWheelSupportTo.LostMouseCapture += new System.Windows.Input.MouseEventHandler(elementToAddMouseWheelSupportTo_LostMouseCapture); //Add a new node to our tree and save a reference to the node for this element elementState = elementStateTree.Add(elementToAddMouseWheelSupportTo, parentElementWithMouseWheelSupport); }
public static void ExecuteOnLoaded(FrameworkElement fe, Action action) { if (fe.IsLoaded) { if (action != null) { action(); } } else { RoutedEventHandler handler = null; handler = delegate { fe.Loaded -= handler; if (action != null) { action(); } }; fe.Loaded += handler; } }
public static void OnClick(FrameworkElement element, Action action, params FrameworkElement[] exclusions) { ClickEvent c = new ClickEvent(action, mainGrid, exclusions); element.MouseLeftButtonDown += c.OnButtonDown; element.MouseLeftButtonUp += c.OnButtonUp; list.Add(c); }
public static void VoteCollapsed(FrameworkElement fe) { foreach (var item in fe.LogicalParents().TakeWhile(a => GetAutoHide(a) == AutoHide.Undefined)) { SetAutoHide(item, AutoHide.Collapsed); } }
/// <summary> /// Replaces the content for a <see cref="DataField"/> with another control and updates the bindings. /// </summary> /// <param name="field">The <see cref="DataField"/> whose <see cref="TextBox"/> will be replaced.</param> /// <param name="newControl">The new control you're going to set as <see cref="DataField.Content" />.</param> /// <param name="dataBindingProperty">The control's property that will be used for data binding.</param> /// <param name="bindingSetupFunction"> /// An optional <see cref="Action"/> you can use to change parameters on the newly generated binding before /// it is applied to <paramref name="newControl"/> /// </param> /// <param name="sourceProperty">The source dependency property to use for the binding.</param> public static void ReplaceContent(this DataField field, FrameworkElement newControl, DependencyProperty dataBindingProperty, Action<Binding> bindingSetupFunction, DependencyProperty sourceProperty) { if (field == null) { throw new ArgumentNullException("field"); } if (newControl == null) { throw new ArgumentNullException("newControl"); } // Construct new binding by copying existing one, and sending it to bindingSetupFunction // for any changes the caller wants to perform Binding newBinding = field.Content.GetBindingExpression(sourceProperty).ParentBinding.CreateCopy(); if (bindingSetupFunction != null) { bindingSetupFunction(newBinding); } // Replace field newControl.SetBinding(dataBindingProperty, newBinding); field.Content = newControl; }
public static void VoteVisible(FrameworkElement fe) { foreach (var item in fe.LogicalParents().TakeWhile(a => GetAutoHide(a) != AutoHide.Visible)) { SetAutoHide(item, AutoHide.Visible); } }
public void ShowControl(FrameworkElement control) { Initialize(new Window()); this.Window.Content = control; ShowWindow(); }
public IClipboardObject AddAsHtml(FrameworkElement fe, Size imageSize, Size imageElementSize) { if (fe == null) throw new NullReferenceException(nameof(fe)); var bmp = fe.RenderToBitmap(imageSize); var img_src = string.Empty; var use_inline_image = false; if (use_inline_image) { // Inline images are not actually supported by Office applications, so don't use it. // maybe in future... var img_data = bmp.ToBitmap().ToArray(); var base64_img_data = Convert.ToBase64String(img_data); img_src = $"data:image/png;charset=utf-8;base64, {base64_img_data}"; } else { // create a temp file with image and use it as a source var tmp = Path.GetTempFileName(); bmp.Save(tmp); img_src = new Uri(tmp, UriKind.Absolute).ToString(); } var html_data = CF_HTML.PrepareHtmlFragment($"<img height=\"{imageElementSize.Height}\" width=\"{imageElementSize.Width}\" src=\"{img_src}\" />"); Data.SetData(DataFormats.Html, html_data); return this; }
public static void CreateIcon(FrameworkElement element, int width, int height, string path) { try { RenderTargetBitmap bmp = new RenderTargetBitmap(width, height, 96, 96, PixelFormats.Pbgra32); bmp.Render(element); string file = path; string Extension = Path.GetExtension(file).ToLower(); BitmapEncoder encoder; if (Extension == ".gif") encoder = new GifBitmapEncoder(); else if (Extension == ".png") encoder = new PngBitmapEncoder(); else if (Extension == ".jpg") encoder = new JpegBitmapEncoder(); else return; encoder.Frames.Add(BitmapFrame.Create(bmp)); using (Stream stm = File.Create(file)) { encoder.Save(stm); } } catch (Exception ex) { MessageBox.Show(ex.Message); } }
/// <summary> /// Get the top and bottom of a TreeViewItem with respect to its parent. /// </summary> /// <param name="item">The item to get the position of.</param> /// <param name="parent">The parent of the item.</param> /// <param name="top">Vertical offset to the top of the item.</param> /// <param name="bottom"> /// Vertical offset to the bottom of the item. /// </param> public static void GetTopAndBottom(this TreeViewItem item, FrameworkElement parent, out double top, out double bottom) { Debug.Assert(item != null, "item should not be null!"); Debug.Assert(parent != null, "parent should not be null!"); GetTopAndBottom(item.HeaderElement ?? item, parent, out top, out bottom); }
public static Visual Print(Visual v, bool canReturn = false) { try { System.Windows.FrameworkElement e = v as System.Windows.FrameworkElement; if (e == null) { return(null); } PrintDialog pd = new PrintDialog(); bool?determiner = true; if (!canReturn) { determiner = pd.ShowDialog(); } if ((bool)determiner) { //store original scale Transform originalScale = e.LayoutTransform; //get selected printer capabilities System.Printing.PrintCapabilities capabilities = pd.PrintQueue.GetPrintCapabilities(pd.PrintTicket); //get scale of the print wrt to screen of WPF visual //double x = capabilities.PageImageableArea.ExtentWidth / e.ActualWidth; //double y = capabilities.PageImageableArea.ExtentHeight / e.ActualHeight; double scale = Math.Min(capabilities.PageImageableArea.ExtentWidth / e.ActualWidth, capabilities.PageImageableArea.ExtentHeight / e.ActualHeight); //Transform the Visual to scale e.LayoutTransform = new ScaleTransform(scale, scale); // e.LayoutTransform = new ScaleTransform(x, y); //get the size of the printer page System.Windows.Size sz = new System.Windows.Size(capabilities.PageImageableArea.ExtentWidth, capabilities.PageImageableArea.ExtentHeight); //update the layout of the visual to the printer page size. e.Measure(sz); e.Arrange(new System.Windows.Rect(new System.Windows.Point(capabilities.PageImageableArea.OriginWidth, capabilities.PageImageableArea.OriginHeight), sz)); //now print the visual to printer to fit on the one page. if (!canReturn) { pd.PrintVisual(v, "My Print"); //apply the original transform. e.LayoutTransform = originalScale; MessageBox.Show("Printing SuccessFul", "Operation Successful", MessageBoxButton.OK, MessageBoxImage.Information); } } if (canReturn) { return(v); } } catch (Exception ex) { MessageBox.Show(ex.Message); } return(null); }
void DragDropPanel_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { System.Windows.FrameworkElement c = sender as System.Windows.FrameworkElement; dragOn = true; beginP = e.GetPosition(null); c.Opacity *= 0.5; c.CaptureMouse(); }
sw.FrameworkElement EmptyCell(int x, int y) { var empty = new sw.FrameworkElement(); swc.Grid.SetColumn(empty, x); swc.Grid.SetRow(empty, y); return(empty); }
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); Callback.OnCellFormatting(Widget, new FormatEventArgs(column.Widget as GridColumn, gridcell, dataItem, row, element)); } }
protected override object PrepareCellForEdit(System.Windows.FrameworkElement editingElement, System.Windows.RoutedEventArgs editingEventArgs) { TextBox edit = editingElement as TextBox; edit.PreviewTextInput += OnPreviewTextInput; return(base.PrepareCellForEdit(editingElement, editingEventArgs)); }
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); }
/// <summary> /// Wraps the specified <paramref name="nativeControl"/> to an Eto control that can be used directly in Eto.Forms code. /// </summary> /// <returns>The eto control wrapper around the native control.</returns> /// <param name="nativeControl">Native control to wrap.</param> public static Control ToEto(this sw.FrameworkElement nativeControl) { if (nativeControl == null) { return(null); } return(new Control(new NativeControlHandler(nativeControl))); }
public void RegisterZoomCanvas(ZoomCanvas canvas, System.Windows.FrameworkElement manipulationElement) { manipulationElement.IsManipulationEnabled = true; manipulationElement.ManipulationStarting += new EventHandler <ManipulationStartingEventArgs>(manipulationElement_ManipulationStarting); manipulationElement.ManipulationDelta += new EventHandler <ManipulationDeltaEventArgs>(manipulationElement_ManipulationDelta); manipulationElement.ManipulationCompleted += new EventHandler <ManipulationCompletedEventArgs>(manipulationElement_ManipulationCompleted); }
public static Size GetSize(this sw.FrameworkElement element) { if (!double.IsNaN(element.ActualWidth) && !double.IsNaN(element.ActualHeight)) { return(new Size((int)element.ActualWidth, (int)element.ActualHeight)); } return(new Size((int)(double.IsNaN(element.Width) ? -1 : element.Width), (int)(double.IsNaN(element.Height) ? -1 : element.Height))); }
protected override bool CommitCellEdit(sw.FrameworkElement editingElement) { var control = editingElement as swc.CheckBox ?? editingElement.FindChild <swc.CheckBox>("control"); Handler.SetValue(control.DataContext, control.IsChecked); Handler.ContainerHandler.CellEdited(Handler, editingElement); return(true); }
private static void PrepareAnimations(FrameworkElement element, bool useSecondaryAnimation = false) { if (element == null) { return; } // Make sure to not start an animation when an element is not visible if (element.Visibility != Visibility.Visible) { return; } // Make sure to stop any running animations if (_actives.IsElementAnimating(GetElementGuid(element))) { foreach (var active in _actives.GetAllNonIteratingActiveTimelines(GetElementGuid(element))) { active.Timeline.Stop(); } } var animationSettings = element.GetSettings( useSecondaryAnimation ? SettingsTarget.Secondary : SettingsTarget.Primary, getPrimaryFunc: GetPrimary, getSecondaryFunc: GetSecondary); // Settings can be null if a Trigger is set before the associated element is loaded if (animationSettings == null) { return; } var settingsList = animationSettings.ToSettingsList(); var startFirst = true; var iterationBehavior = GetIterationBehavior(element); var iterationCount = GetIterationCount(element); var sequenceCounter = 0; foreach (var settings in settingsList) { var isSequence = settingsList.Count > 1; // The "first" animation must always run immediately if (startFirst) { RunAnimation(element, settings, isSequence); startFirst = false; } else { _actives.Add(null, settings, element, AnimationState.Idle, iterationBehavior, iterationCount, isSequence, sequenceOrder: sequenceCounter); } sequenceCounter++; } }
public override void Remove(sw.FrameworkElement child) { var x = swc.Grid.GetColumn(child); var y = swc.Grid.GetRow(child); Control.Children.Remove(child); controls[x, y] = null; UpdatePreferredSize(); }