/// <summary> /// An event reporting that the IsKeyboardFocusWithin property changed. /// </summary> protected override void OnIsKeyboardFocusWithinChanged(DependencyPropertyChangedEventArgs e) { base.OnIsKeyboardFocusWithinChanged(e); // When focus within changes we need to update the value of IsSelectionActive. bool isSelectionActive = false; bool isKeyboardFocusWithin = IsKeyboardFocusWithin; if (isKeyboardFocusWithin) { // Keyboard focus is within the control, selection should appear active. isSelectionActive = true; } else { DependencyObject currentFocus = Keyboard.FocusedElement as DependencyObject; if (currentFocus != null) { UIElement root = KeyboardNavigation.GetVisualRoot(this) as UIElement; if (root != null && root.IsKeyboardFocusWithin) { if (FocusManager.GetFocusScope(currentFocus) != root) { isSelectionActive = true; } } } } if ((bool)GetValue(Selector.IsSelectionActiveProperty) != isSelectionActive) { // The value changed, set the new value. SetValue(Selector.IsSelectionActivePropertyKey, BooleanBoxes.Box(isSelectionActive)); } if (isKeyboardFocusWithin && IsKeyboardFocused && (_selectedContainer != null) && !_selectedContainer.IsKeyboardFocusWithin) { _selectedContainer.Focus(); } }
private void button_Restart_Click(object sender, RoutedEventArgs e) { if (listView_clients.SelectedItems.Count > 0) { foreach (Client client in listView_clients.SelectedItems) { Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background, (DispatcherOperationCallback) delegate(object o) { client.ToShutdown("2"); return(null); }, null); } } else { MessageBox.Show("Не выбран ни один клиент", "", MessageBoxButton.OK, MessageBoxImage.Information); } var scope = FocusManager.GetFocusScope(sender as Button); // elem is the UIElement to unfocus FocusManager.SetFocusedElement(scope, null); // remove logical focus Keyboard.ClearFocus(); // remove keyboard focus }
/// <summary> /// Method to handle the preview key down. /// </summary> /// <param name="e">KeyEvent arguments.</param> protected override void OnPreviewKeyDown(KeyEventArgs e) { base.OnPreviewKeyDown(e); var fs = FocusManager.GetFocusScope(this); var o = FocusManager.GetFocusedElement(fs); if (e.Key == Key.Escape) { PopupControl.IsOpen = false; Focus(); e.Handled = true; } else if (e.Key == Key.Down) { if (listBox != null && o == this) { raiseTextChanged = true; listBox.Focus(); raiseTextChanged = false; } } }
private void RestorePreviousFocus() { if (this.IsKeyboardFocusWithin) { Keyboard.Focus(null); FocusManager.SetFocusedElement(this, null); } DependencyObject parent = this.Parent; if (parent != null) { DependencyObject focusScope = FocusManager.GetFocusScope(parent); if (focusScope != null) { IInputElement focusedElement = FocusManager.GetFocusedElement(focusScope); if (this.ElementIsWithin(focusedElement)) { FocusManager.SetFocusedElement(focusScope, null); } } } }
private async void Start_Click(object sender, RoutedEventArgs e) { var dialog = new HitsoundStudioExportDialog(Settings); var result = await DialogHost.Show(dialog, "RootDialog"); if (!(bool)result) { return; } if (Settings.BaseBeatmap == null || Settings.DefaultSample == null) { MessageBox.Show("Please select a base beatmap and default hitsound first."); return; } // Remove logical focus to trigger LostFocus on any fields that didn't yet update the ViewModel FocusManager.SetFocusedElement(FocusManager.GetFocusScope(this), null); BackgroundWorker.RunWorkerAsync(Settings); CanRun = false; }
private void Tab_ResetFocus(object sender, EventArgs e) { if (sender is TabControl || sender is TabItem) { RxApp.MainThreadScheduler.Schedule(() => { IInputElement focusedControl = FocusManager.GetFocusedElement(this); if (focusedControl is TextBox textBox) { // Move to a parent that can take focus FrameworkElement parent = (FrameworkElement)textBox.Parent; while (parent != null && parent is IInputElement && !((IInputElement)parent).Focusable) { parent = (FrameworkElement)parent.Parent; } DependencyObject scope = FocusManager.GetFocusScope(textBox); FocusManager.SetFocusedElement(scope, parent as IInputElement); } }); } }
private void PageDir_KeyDown(object sender, KeyEventArgs e) { if (e.Key == Key.Enter) { if (InvalidChars.All(PageDir.Text.Contains)) { MessageBox.Show("The specified path is invalid.", "Invalid Path"); } //No Regex match "new Regex(@"^[<>;*?|]$").IsMatch(PageDir.Text)" else { try { VisitedDirectories.Add(PageDir.Text.Replace("\"", "").Replace("\\\\", "\\").Replace("\\", "\\\\")); PageDir.Text = VisitedDirectories.Last().Replace("\\\\", " > "); Keyboard.ClearFocus(); FocusManager.SetFocusedElement(FocusManager.GetFocusScope(PageDir), null); IndexFiles(VisitedDirectories.Last()); } catch (Exception ex) { MessageBox.Show(ex.ToString(), "Error indexing directory"); } } } }
/// <summary> /// Begins the edit. /// </summary> private void BeginEdit() { if (this.textBox != null) { throw new InvalidOperationException(); } var scope = FocusManager.GetFocusScope(this); this.oldfocus = FocusManager.GetFocusedElement(scope); this.textBox = new TextBox(); this.textBox.SetBinding( TextBox.TextProperty, new Binding("Text") { Source = this, UpdateSourceTrigger = UpdateSourceTrigger.Explicit }); Grid.SetColumn(this.textBox, Grid.GetColumn(this)); Grid.SetColumnSpan(this.textBox, Grid.GetColumnSpan(this)); this.Visibility = Visibility.Collapsed; var p = this.Parent as Panel; if (p != null) { int index = p.Children.IndexOf(this); p.Children.Insert(index, this.textBox); } this.textBox.HorizontalAlignment = this.HorizontalAlignment; this.textBox.VerticalAlignment = this.VerticalAlignment; this.textBox.HorizontalContentAlignment = this.HorizontalContentAlignment; this.textBox.VerticalContentAlignment = this.VerticalContentAlignment; this.textBox.LostFocus += this.TextBoxLostFocus; this.textBox.KeyDown += this.TextBoxKeyDown; this.textBox.CaretIndex = this.textBox.Text.Length; this.textBox.SelectAll(); this.textBox.Focus(); }
/// <summary> /// Visual Studio 2012 introduced a new form of incremental search in the find / replace UI /// implementation. It doesn't implement the IIncrementalSearch interface and doesn't expose /// whether or not it's active via any public API. /// /// The best way to find if it's active is to look for the adornment itself and see if it or /// it's descendant has focus. Because Visual Studio is using WPF hosted in a HWND it doesn't /// actually have keyboard focus, just normal focus /// </summary> internal bool IsIncrementalSearchActive2012(ITextView textView) { var wpfTextView = textView as IWpfTextView; if (wpfTextView == null) { return(false); } var adornmentLayer = wpfTextView.GetAdornmentLayerNoThrow("FindUIAdornmentLayer", s_findUIAdornmentLayerKey); if (adornmentLayer == null) { return(false); } foreach (var element in adornmentLayer.Elements) { var adornment = element.Adornment; if (adornment.Visibility == Visibility.Visible && adornment.GetType().Name == "FindUI") { var scope = FocusManager.GetFocusScope(adornment); if (scope == null) { continue; } var focusedElement = FocusManager.GetFocusedElement(scope) as UIElement; if (focusedElement != null && focusedElement != wpfTextView.VisualElement && focusedElement.IsDescendantOf(adornment)) { return(true); } } } return(false); }
public FileBrowserView(FileInfoBase[] fileInfos, Modes mode) { this.mode = mode; this.fileInfos = fileInfos; this.InitializeComponent(); this.ContentArea.DataContext = this; foreach (FileInfoBase info in fileInfos) { IFileSource?source = info.GetFileSource(); this.FileSources.Add(source); } this.FileSource = this.GetDefaultFileSource(); this.IsOpen = true; if (this.mode == Modes.Save) { this.FileName = "New " + fileInfos[0].Name; Task.Run(async() => { await Task.Delay(100); Application.Current.Dispatcher.Invoke(() => { this.FileNameInputBox.Focus(); this.FileNameInputBox.SelectAll(); FocusManager.SetFocusedElement(FocusManager.GetFocusScope(this), this.FileNameInputBox); Keyboard.Focus(this.FileNameInputBox); }); }); } Task.Run(this.UpdateEntries); }
private static void OnKeyDown(object sender, KeyEventArgs e) { if (e.Key == Key.Return || e.Key == Key.Enter) { var textBox = sender as TextBoxBase; if (textBox == null) { return; } if (textBox.GetMoveFocusOnEnter()) { // MoveFocus takes a TraversalRequest as its argument. var request = new TraversalRequest(FocusNavigationDirection.Next); // Gets the element with keyboard focus. var elementWithFocus = Keyboard.FocusedElement as UIElement; // Change keyboard focus. if (elementWithFocus != null) { if (elementWithFocus.MoveFocus(request)) { e.Handled = true; } } } if (textBox.IsFocused && textBox.GetLoseFocusOnEnter()) { var focusableAncestor = textBox.Ancestors() .OfType <IInputElement>() .FirstOrDefault(x => x.Focusable); var scope = FocusManager.GetFocusScope(textBox); FocusManager.SetFocusedElement(scope, focusableAncestor); } } }
void TreeViewItem_Selected(object sender, RoutedEventArgs e) { if (e.OriginalSource is TreeViewItem tvi) { for (var parent = VisualTreeHelper.GetParent(tvi); parent != null; parent = VisualTreeHelper.GetParent(parent)) { if (parent is TreeViewItem parentTVI) { parentTVI.IsExpanded = true; } } DependencyObject scope = FocusManager.GetFocusScope(tvi); if (FocusManager.GetFocusedElement(scope) is TreeViewItem focused) { TreeView curr = GetTreeView(focused); if (curr == null || curr == GetTreeView(tvi)) { FocusManager.SetFocusedElement(scope, tvi); } } } }
private void Window_MouseDown(object sender, MouseButtonEventArgs e) { mainW.Focus(); // Kill logical focus FocusManager.SetFocusedElement(FocusManager.GetFocusScope(mainW), null); // Kill keyboard focus Keyboard.ClearFocus(); //move if (Mouse.LeftButton == MouseButtonState.Pressed) { try { this.DragMove(); } catch (Exception ex) { #if DEBUG MessageBox.Show("DEBUG: " + ex.ToString()); //throw; #endif //System.InvalidOperationException //dragdrop with only leftclick //dragdrop must be with pressed click } } }
public void ShouldResetTextOnLostFocus() { var textBox = new TextBox(); var textBox2 = new TextBox(); var grid = new Grid(); grid.Children.Add(textBox); grid.Children.Add(textBox2); var command = new MockCommand(); TestableReturnCommandBehavior behavior = new TestableReturnCommandBehavior(textBox); behavior.Command = command; behavior.DefaultTextAfterCommandExecution = "DefaultText"; textBox.Focus(); DependencyObject scope = FocusManager.GetFocusScope(textBox); FocusManager.SetFocusedElement(scope, textBox2 as IInputElement); Assert.AreEqual("DefaultText", textBox.Text); }
private void OnTick(object sender, EventArgs e) { _switchTimer.Stop(); if (!TryGetDevicePosition(_device, out Point endPosition)) { return; } if (new Vector(endPosition.X - _startPosition.X, endPosition.Y - _startPosition.Y).Length > Tolerance) { return; } this.IsReadOnly = false; // Get focus. var scope = FocusManager.GetFocusScope(this); FocusManager.SetFocusedElement(scope, this); Keyboard.Focus(this); this.SelectionStart = 0; }
private void Label_MouseUp(object sender, MouseButtonEventArgs e) { DependencyObject scope = FocusManager.GetFocusScope(this); IInputElement currFocus = FocusManager.GetFocusedElement(scope); if ((currFocus != null)) { if (currFocus == m_lastFocus) { IsEditing = true; } else { m_lastFocus = currFocus; DependencyObject observedObject = currFocus as DependencyObject; if (observedObject != null) { m_lastFocus.LostKeyboardFocus += ObservedElementLostFocus; m_lastFocus.KeyUp += ObservedElement_KeyUp; // THIS IS THE TRICK } } } }
private void CreateSession(object sender, RoutedEventArgs e) { Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background, (DispatcherOperationCallback) delegate(object o) { if (listView_clients.SelectedItems.Count > 0) { bool toCreate = true; foreach (Client client in listView_clients.SelectedItems) { if (client.IsSessionStarted) { toCreate = MessageBox.Show("Будет создан новый сеанс. Продолжить?", "", MessageBoxButton.YesNo, MessageBoxImage.Information) == MessageBoxResult.Yes ? true : false; break; } } if (toCreate) { var wnd = new SessionCreationView { Owner = this }; wnd.View(listView_clients.SelectedItems); } } else { MessageBox.Show("Не выбран ни один клиент", "", MessageBoxButton.OK, MessageBoxImage.Information); } if (sender is Button) { var scope = FocusManager.GetFocusScope(sender as Button); // elem is the UIElement to unfocus FocusManager.SetFocusedElement(scope, null); // remove logical focus Keyboard.ClearFocus(); // remove keyboard focus } return(null); }, null); }
private void StopSearch(bool stealFocus) { if (stealFocus) { DependencyObject scope = FocusManager.GetFocusScope(this); FocusManager.SetFocusedElement(scope, null); Application.Current.MainWindow.Focus(); } if (IsPerformingSearch) { if (RequiresExplicitSearchStart) { ICommand command = StopSearchCommand; if (command != null && command.CanExecute(null)) { command.Execute(null); } } } IsPerformingSearch = false; Text = null; }
/// <summary> /// Invoked when a GotKeyboardFocus attached event reaches this element in its route. /// </summary> /// <param name="e">The KeyboardFocusChangedEventArgs that contains the event data.</param> protected override void OnGotKeyboardFocus(KeyboardFocusChangedEventArgs e) { // Validate the parameters. if (e == null) { throw new ArgumentNullException("e"); } // The focus is given to the content on initialization. This allows the parent of this page to set the focus on the page without having to know about // the inner structure and who should get the focus once the page has been selected. if (e.NewFocus == this) { DependencyObject focusScope = FocusManager.GetFocusScope(this); IInputElement focusedElement = FocusManager.GetFocusedElement(focusScope); if (focusedElement == null) { IInputElement contentElement = this.Content as IInputElement; if (contentElement != null) { FocusManager.SetFocusedElement(focusScope, contentElement); } } } }
/// <summary> /// Sets the styles, templates, and bindings for a ListViewItem. /// </summary> /// <param name="element">An object that is a ListViewItem or that can be converted into one.</param> /// <param name="item">The object to use to create the ListViewItem.</param> protected override void PrepareContainerForItemOverride(DependencyObject element, object item) { // Extract the specific arguments from the generic event arguments. ListBoxItem listBoxItem = element as ListBoxItem; // This will select the first item in a new items source. if (this.selectNextElement) { this.selectNextElement = false; listBoxItem.IsSelected = true; } // If the focus operation has been deferred, then now is the time to move the focus into the newly created item. This is the first and only place where // we get a notification of a new child element so it's the first chance we have to give it the focus. if (this.IsFocused && this.focusNextElement) { this.focusNextElement = false; DependencyObject focusScope = FocusManager.GetFocusScope(this); FocusManager.SetFocusedElement(focusScope, listBoxItem); } // Allow the base class to finish preparing the item. base.PrepareContainerForItemOverride(element, item); }
/// <summary> /// Attempts to force focus to the bound property with the same propertyPath /// as the propertyPath input /// </summary> /// <param name="elementBinding">Binding to evaluate</param> /// <param name="propertyPath">propertyPath to try and find finding for</param> /// <param name="isUsingDataWrappers">shoul be true if the property is bound to a /// <c>Cinch.DataWrapper</c></param> protected virtual void ConductFocusOnElement(Binding elementBinding, String propertyPath, bool isUsingDataWrappers) { if (elementBinding == null) { return; } if (isUsingDataWrappers) { if (!elementBinding.Path.Path.Contains(propertyPath)) { return; } } else { if (elementBinding.Path.Path != propertyPath) { return; } } // Delay the call to allow the current batch // of processing to finish before we shift focus. AssociatedObject.Dispatcher.BeginInvoke((Action) delegate { if (!AssociatedObject.Focus()) { DependencyObject fs = FocusManager.GetFocusScope(AssociatedObject); FocusManager.SetFocusedElement(fs, AssociatedObject); } }, DispatcherPriority.Background); }
// When popup loses focus but isn't hidden, store the last element that had focus so we can put it back later void OnLostFocus(object sender, RoutedEventArgs e) { var focusScope = FocusManager.GetFocusScope(this); lastFocusControl = FocusManager.GetFocusedElement(focusScope) as UIElement; }
public static object GetFocusedElement(DependencyObject referenceObject) { var scope = FocusManager.GetFocusScope(referenceObject) ?? GetCurrentWindow(); return(scope != null?FocusManager.GetFocusedElement(scope) : null); }
// When popup loses focus but isn't hidden, store the last element that had focus so we can put it back later void PopupPanel_LostFocus(object sender, RoutedEventArgs e) { DependencyObject focusScope = FocusManager.GetFocusScope(this); _lastFocusControl = FocusManager.GetFocusedElement(focusScope) as UIElement; }
private void button_changeSession_Click(object sender, RoutedEventArgs e) { Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background, (DispatcherOperationCallback) delegate(object o) { if (listView_clients.SelectedItems.Count > 0) { bool isDifferent = false; bool isNotValidToEdit = false; bool isFirst = true; bool isInternetSession = false; DateTime expireDate = DateTime.Now; SessionTariff tarrif = new SessionTariff(); Double payment = 0; foreach (Client client in listView_clients.SelectedItems) { if (client.EndSession.HasValue && client.Tariff.LimitedTimeMode) { if (isFirst) { payment = client.TotalPayment; expireDate = client.EndSession.Value; tarrif = client.Tariff; isInternetSession = client.IsInternetSession; isFirst = false; } else { if (!isDifferent) { if (!( expireDate < client.EndSession.Value.AddSeconds(5) && expireDate > client.EndSession.Value.AddSeconds(-5) && tarrif.Equals(client.Tariff) && isInternetSession.Equals(client.IsInternetSession) )) { isDifferent = true; } } } } else { isNotValidToEdit = true; break; } } if (isNotValidToEdit) { if (MessageBox.Show("Будет создан новый сеанс. Продолжить?", "", MessageBoxButton.YesNo, MessageBoxImage.Information) == MessageBoxResult.Yes) { var wnd = new SessionCreationView { Owner = this }; wnd.View(listView_clients.SelectedItems); } } else { if (!isDifferent) //сеансы одинаковые { var wnd = new SessionExtensionView { Owner = this }; wnd.View(listView_clients.SelectedItems, expireDate, tarrif, payment); } else { MessageBox.Show("Сеансы различны и не могут быть изменены!\nПопробуйте добавить платеж или время.", "", MessageBoxButton.OK, MessageBoxImage.Warning); } } } else { MessageBox.Show("Не выбран ни один клиент", "", MessageBoxButton.OK, MessageBoxImage.Information); } var scope = FocusManager.GetFocusScope(sender as Button); // elem is the UIElement to unfocus FocusManager.SetFocusedElement(scope, null); // remove logical focus Keyboard.ClearFocus(); // remove keyboard focus return(null); }, null); }
private void Window_ContentRendered(object sender, EventArgs e) { KeyDown += (_, e) => Shortcuts.GenericWindowShortcuts.KeysDown(null, e, this); // Hack to deselect border on mouse click MouseLeftButtonDown += delegate { FocusManager.SetFocusedElement(FocusManager.GetFocusScope(this), null); Keyboard.ClearFocus(); Focus(); }; // CloseButton CloseButton.TheButton.Click += delegate { Hide(); ConfigureWindows.GetMainWindow.Focus(); }; // MinButton MinButton.TheButton.Click += delegate { SystemCommands.MinimizeWindow(this); }; TitleBar.MouseLeftButtonDown += delegate { DragMove(); }; MainBackground.MouseLeftButtonDown += delegate { DragMove(); }; // FileProperties FileProperties.PreviewMouseLeftButtonDown += delegate { PreviewMouseButtonDownAnim(FilePropertiesFill); }; FileProperties.MouseEnter += delegate { ButtonMouseOverAnim(FilePropertiesFill); }; FileProperties.MouseEnter += delegate { AnimationHelper.MouseEnterBgTexColor(FilePropertiesBrush); }; FileProperties.MouseLeave += delegate { ButtonMouseLeaveAnim(FilePropertiesFill); }; FileProperties.MouseLeave += delegate { AnimationHelper.MouseLeaveBgTexColor(FilePropertiesBrush); }; FileProperties.Click += delegate { SystemIntegration.NativeMethods.ShowFileProperties(Pics[FolderIndex]); }; // Print Print.PreviewMouseLeftButtonDown += delegate { PreviewMouseButtonDownAnim(PrintFill); }; Print.MouseEnter += delegate { ButtonMouseOverAnim(PrintFill); }; Print.MouseEnter += delegate { AnimationHelper.MouseEnterBgTexColor(PrintBrush); }; Print.MouseLeave += delegate { ButtonMouseLeaveAnim(PrintFill); }; Print.MouseLeave += delegate { AnimationHelper.MouseLeaveBgTexColor(PrintBrush); }; Print.Click += delegate { FileHandling.Open_Save.Print(Pics[FolderIndex]); }; // OpenWith OpenWith.PreviewMouseLeftButtonDown += delegate { PreviewMouseButtonDownAnim(OpenWithFill); }; OpenWith.MouseEnter += delegate { ButtonMouseOverAnim(OpenWithFill); }; OpenWith.MouseEnter += delegate { AnimationHelper.MouseEnterBgTexColor(OpenWithBrush); }; OpenWith.MouseLeave += delegate { ButtonMouseLeaveAnim(OpenWithFill); }; OpenWith.MouseLeave += delegate { AnimationHelper.MouseLeaveBgTexColor(OpenWithBrush); }; OpenWith.Click += delegate { FileHandling.Open_Save.OpenWith(Pics[FolderIndex]); }; // ShowInFoler ShowInFoler.PreviewMouseLeftButtonDown += delegate { PreviewMouseButtonDownAnim(ShowInFolerFill); }; ShowInFoler.MouseEnter += delegate { ButtonMouseOverAnim(ShowInFolerFill); }; ShowInFoler.MouseEnter += delegate { AnimationHelper.MouseEnterBgTexColor(ShowInFolerBrush); }; ShowInFoler.MouseLeave += delegate { ButtonMouseLeaveAnim(ShowInFolerFill); }; ShowInFoler.MouseLeave += delegate { AnimationHelper.MouseLeaveBgTexColor(ShowInFolerBrush); }; ShowInFoler.Click += delegate { FileHandling.Open_Save.Open_In_Explorer(); }; FilenameCopy.TheButton.Click += delegate { Clipboard.SetText(FilenameBox.Text); }; FolderCopy.TheButton.Click += delegate { Clipboard.SetText(FolderBox.Text); }; FullpathCopy.TheButton.Click += delegate { Clipboard.SetText(FullPathBox.Text); }; CreatedCopy.TheButton.Click += delegate { Clipboard.SetText(CreatedBox.Text); }; ModifiedCopy.TheButton.Click += delegate { Clipboard.SetText(ModifiedBox.Text); }; SizePxCopy.TheButton.Click += delegate { Clipboard.SetText(SizePxBox.Text); }; SizeMpCopy.TheButton.Click += delegate { Clipboard.SetText(SizeMpBox.Text); }; DpiCopy.TheButton.Click += delegate { Clipboard.SetText(ResolutionBox.Text); }; PrintSizeCmCopy.TheButton.Click += delegate { Clipboard.SetText(PrintSizeCmBox.Text); }; PrintSizeInCopy.TheButton.Click += delegate { Clipboard.SetText(PrintSizeInBox.Text); }; AspectRatioCopy.TheButton.Click += delegate { Clipboard.SetText(AspectRatioBox.Text); }; if (Pics.Count > 0) { UpdateValues(); } }
private void OnMouseLeave(object sender, MouseEventArgs e) { var scope = FocusManager.GetFocusScope(this.AssociatedObject); FocusManager.SetFocusedElement(scope, this.AssociatedObject); // UIElement.Focus method is not enough. }
private void button_addPaymentToSession_Click(object sender, RoutedEventArgs e) { Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background, (DispatcherOperationCallback) delegate(object o) { if (listView_clients.SelectedItems.Count > 0) { bool isDifferent = false; bool isNotValidToEdit = false; bool isFirst = true; bool isInternetSession = false; SessionTariff tarrif = new SessionTariff(); Double payment = 0; foreach (Client client in listView_clients.SelectedItems) { if (client.EndSession.HasValue && client.Tariff.LimitedTimeMode) { if (isFirst) { payment = client.TotalPayment; tarrif = client.Tariff; isInternetSession = client.IsInternetSession; isFirst = false; } else { if (!isDifferent) { if (!( tarrif.Equals(client.Tariff) && isInternetSession.Equals(client.IsInternetSession) )) { isDifferent = true; } } } } else { isNotValidToEdit = true; break; } } if (isNotValidToEdit) { if (MessageBox.Show("Будет создан новый сеанс. Продолжить?", "", MessageBoxButton.YesNo, MessageBoxImage.Information) == MessageBoxResult.Yes) { var wnd = new SessionCreationView { Owner = this }; wnd.View(listView_clients.SelectedItems); } } else { var wnd = new PaymentEditionView { Owner = this }; if (isDifferent) { wnd.View(listView_clients.SelectedItems); } else { wnd.View(listView_clients.SelectedItems, tarrif, isInternetSession); } } } else { MessageBox.Show("Не выбран ни один клиент", "", MessageBoxButton.OK, MessageBoxImage.Information); } var scope = FocusManager.GetFocusScope(sender as Button); // elem is the UIElement to unfocus FocusManager.SetFocusedElement(scope, null); // remove logical focus Keyboard.ClearFocus(); // remove keyboard focus return(null); }, null); }
static void lbi_MouseEnter(object sender, System.Windows.Input.MouseEventArgs e) { ListBoxItem lbi = (ListBoxItem)sender; lbi.IsSelected = true; var listBox = ListBox.ItemsControlFromItemContainer(lbi); FrameworkElement focusedElement = (FrameworkElement)FocusManager.GetFocusedElement(FocusManager.GetFocusScope(listBox)); if (focusedElement != null && focusedElement.IsDescendantOf(listBox)) { lbi.Focus(); } }
public static bool IsInMainFocusScope(this DependencyObject element) { var focusScope = FocusManager.GetFocusScope(element) as Visual; return(focusScope == null || VisualTreeHelper.GetParent(focusScope) == null); }