Home » WPF

How do you dim a WPF page to bring to focus something I want to user to interact with?

In the WPF app I'm writing, to replace an old VB6 app, there are a few places in the app in which it has to collect some text data from the user.  Let me explain.

In the old VB6 app we've got several combo boxes which lists all of the items that the user can select from.  However, since this is for an intake situation, sometimes the clients that the user of our application is working with, will say something which isn't in the dropdown, nor is it in the database.  In such situations the user selects "Other", and then a simple Windows dialog box pops up, asking the user to enter whatever it is that is new, that the client is telling them.  This gets stored in a separate table for these exceptional cases.

This paradigm has worked fine for the last 15 years.  However, user interfaces have changed, and I believe users expectations have too.  What I would like to do is something I've seen done dozens of times on websites.  Sometimes, when the user does something which requires the user to pay particular attention to it, then the whole web page fades and then the thing the user is supposed to work with is front and center.  My guess is what's going on is the web designer has put a hidden <div> element on the page, and then when the user has to do something special, the page fades and, using JavaScript the hidden <div> element is made visible and is centered on the page.  That way the user knows they've got to enter data, or whatever, and click on some sort of OK button.  Then the data is put wherever it's got to go and this <div> element is made invisible again, and lastly the page is no longer made dim.

I would like to do the same thing with WPF, but how do I do that?


4 Answers Found


Answer 1

I've not yet tried to do it, but you could actually use a very similar technique to that which you described...make a Grid or Panel the size of the window or page  and give it a background color like gray or something...have it's opacity set to 0 and you can then animate the opacity to say .5 or so at the time you want your background to become gray.  It should be a pretty straight forward implementation...just remember to put  your grid/panel on top of the rest of your controls (ie. at the bottom of the window/page's xaml).


Hope it helps,



Answer 2

Yep, to add to what Aj said, you may wish to alter the ZIndex of the dimming rectangle and focused control so the control is on top, then the dimming rectangle, then the rest of the control on the window/page.


I suppose you could also use 4 rectangles, and position them around the control you want lit up.


Answer 3

I've got some follow-up questions that I'd like to ask.  First, I like what you said here, Matt, about specifying the ZOrder for the control on top of the border.  Unfortunately, for me, it appears to still be as dimmed as the border is, and I'm not sure how to fix that.  The XAML is small enough, so I'm going to include it all here:

<Window x:Class="SimpleWPFwithDimming.Window1"
  Title="Window1" Height="400" Width="400">
		<TextBlock Height="21" Margin="120,42,138,0" Name="textBlock1" VerticalAlignment="Top" Text="This is some text" />
		<Button Margin="82,84,75,0" Name="btnDoSomething" Click="btnDoSomething_Click" Height="29" VerticalAlignment="Top">Bring up the dialog  box (or whatever)</Button>
		<Border Name="theShadowbox" VerticalAlignment="Center" HorizontalAlignment="Center" Background="Black"
						Opacity="0.50" Width="378" Height="362" Visibility="Collapsed" Panel.ZIndex="10">
			<local:UserControlTest x:Name="ucMyControl" WeAreDone="ucMyControl_WeAreDone" Panel.ZIndex="12" />

Second, how do I make the user  control resize properly as the user resizes the main window (Window1)?



Answer 4

Sure. In response to the first question, you've specified ucMyControl to be a child of 'theShadowBox' Border, therefore ucMyControl will always be drawn *under* that border if you get me. You don't have to make ucMyControl a child of that border, it can just be another child of the Grid, but you could also use a DataTrigger to set the Visibility of it if you wanted.


The reason the UserControl is not resizing is because you've hardcoded a size for the Border it's a child of. 

<BorderName="theShadowbox"VerticalAlignment="Center"HorizontalAlignment="Center"Background="Black" Opacity="0.50"Width="378"Height="362"Visibility="Collapsed"Panel.ZIndex="10"><local:UserControlTestx:Name="ucMyControl"WeAreDone="ucMyControl_WeAreDone"Panel.ZIndex="12"/></Border>

Just remove the Height=/Width= ( they'll default to 'Auto'), and everything should resize correctly.

Warm regards,



I have a user control that consists of a dockpanel, inside of which are a textbox, a stack panel (containing two user controls), and another user control.  I am handling the LostFocus event for the dockpanel.  Since LostFocus deals with Logical Focus in WPF parlance, one would logically (pun intended) assume that if one was to click anywhere inside the dockpanel, the LostFocus event should NOT be fired for that control.  However, it appears that If I click anywhere outside of the textbox in the dockpanel, the LostFocus event is fired.  I am not using custom focus scopes since there are multiple of these user controls in my WPF window and I only want one of them to have focus at any given time.

I've read many blogs and articles on WPF focus issues and so far nothing has worked.  Any help would be highly appreciated.


I am facing the focus issue on IE 8 browser and have searched internet a lot but couldn’t find any solution yet.

Here’s the problem description.

I have multiple IE windows open into my project. I am using JavaScript to perform the navigation on the IE window.

Whenever the main IE window makes a navigation to any of the IE windows, it is trying to bring that window to forefront using window.focus() method.

It works in IE 7 without any issues but IE 8 doesn’t seem to bring the window to forefront.

Here’s the sample code snippet of what I do.


function PerformNavigation(url, currentWindow)


    var windowClosed = IsWindowClosed(currentWindow);


    if (windowClosed)




    if (currentWindow != null )


        // Redirect window

        currentWindow.location.href = url;


        //Firefox - would work only if "Raise or lower windows" setting is enabled, Works with IE





If this is not right forum to post this kind of questions, my apologies. Please let me know where to post.

I would really appreciate if you could help.

Thanks for your time.



Jayesh Modha



I have a small problem here. On my WinForm, when I click on Mode1, then a FlowLayoutPanel's visible property is False.

The picture boxes on the Form respond correctly to the Click event as expected.

On the other hand if I click on Mode2, then the FlowLaoutPanel's reappears and the *I suppose* the focus is on of the TextBoxes in the FlowLayoutPanel and PictureBoxes on the Form stop responding to the click event.

What is to be done?


Hi All,

I have been writting an WPF application which allows enduser navigating to controls which being bound to an invalid data by clicking on buttons named "Goto Prev Err" and "Goto Next Err". The implementation was written in codebehind by calling Focus method. However the rectangle focus is invisible when a control gets focus via either one of two upon buttons. I tried moving the focus around controls in my view via pressing the "TAB" and I could see that rectangle.

Do you guys have any ideas about that ??? I do appreciate.


var control2Focus = _controls.FirstOrDefault(item => this.IsErrorFile(item) && callback.Invoke((int)item.Key));

if (control2Focus != null) {
    _currErrPos = (int)control2Focus.Key;
    // (control2Focus.Value as Control).Focus();
    Keyboard.Focus(control2Focus.Value as Control);



Hi Senior,

I just start reading asp coding and i found that some place use dim and some use Dim. Is there difference for small letter and capital letter of d?

Thanks ahead.



I am using Access 2003 VBA and for a specific .mdb, I wish to set the printer to a specific non-networked printer at my desk.

I found code online to do this:

Set Application.Printer = Application.Printers(strDefaultPrinter)


Set Application.Printer = Application.Printers("DTC400e Card Printer")

For either line above, the error reads:  "Method or data member not found" and the debugger highlights the second .Printers.  When I type in '= Application.' Printers is not available as a selection.


I decided to investigate, and found on the MSDN site (http://msdn.microsoft.com/en-us/library/Aa139946) the following code.  It errors also:

Dim prt As Printer
For Each prt In Application.Printers
    Me!cboPrinter.AddItem Item:=prt.DeviceName
Next prt

End Sub

This errors as: "Compile error: User defined type not defined" and the debugger highlights the prt As Printer after the DIM.

I think I am missing a Library, but I cannot figure out which one.  Here is what I have (including some I thought might work based on fruitless internet searches)

Visual Basic for Applications

Microsoft Word 11.0 Object Library

OLE Automation


Microsoft 11.0 Object Library

Microsoft Visual Basic for Applications Extensibility 5.3

Microsoft Scripting Runtime

I would appreciate it if anyone can tell me why I cannot use Application.Printers or even declare a printer - and then how to fix this.



I have followed a good tutorial on adding a custom task pane to outlook e-mails (shows and allows the task pane to be toggled), now I want to populate dropdown boxes when a new e-mail is opened. The dropdown information comes from a database, so I am using a data adapter to pull that information. So in short I would like to open a new e-mail and then populate the task pane custom controls with information to allow the user to interact with them and then press a button to add data to the database (all with-int he custom task pane).


Is it possible to allow interact with desktop on a service without it being the local user ?

The context is a legacy GUI application which although doesn't need interactive input, does allow status info etc to be displayed.

Using the local account works fine for the "test" and works on 2003, vista, windows 7 and 2008 (although the later ones have a separate session 0).

However for the program to truely work it needs network access for the clients that connect to it and for network file access. Is this possible ?

My understanding is the local account does not allow this.

Can we win, have desktop interaction and a service with a non local account ?




I want to use WPF user control inside Visual Studio Option page. I inherited the class from DialogPage. Property "Window" returns my own class derived from System.Windows.Forms.UserControl, which contains ElementHost. Inside this element host a System.Windows.Controls.UserControl is added. Everything seems fine, but the textbox inside user control does not process keyboard events (Backspace, Delete work fine but no other key is working). Buttons work too.

I found some hints about message loop sharings, but everything I tried did not work. May somebody please help me with this and provide some hint about how to implement this message loop sharing? (this seems too complicated for me and I was unable to get it working.



I am developing a WPF Applciation.

I have a User control ucQtyPrice with two simple textboxes which accept user input.

I placed this user control on my WPF Page  in a grid.I have a Add button which when clicked adds a new instance of the User Control ucQtyPrice to the grid.

I can add the user control mutliple times and also remove it.

But i have to read the textbox values from all the instances of this User control.

How can i accomplish that ?




I created a new Wiki Page Library a couple of days ago called "Team Wiki". After playing around with the wiki pages a bit. The default Quick Launch item for the wiki was called "Team Wiki" on the left navigation bar in the default theme. The link when I hover over the "Team Wiki" text points to ".../Team%20Wiki/" which it always has. However, when I click the link it takes me to the URL ".../Team%20Wiki/Forms/AllPages.aspx" instead of the URL ".../Team%20Wiki/Home.aspx" which it used to by default a couple of days ago. Is there any way for me to get my default Quick Launch item to point back to the URL ".../Team%20Wiki/Home.aspx"? The default Home.aspx page is still in the same location as the How%20To%20Use%20This%20Wiki%20Site.aspx page is.


  I have a listBox whose elements are binded using ItemsSouce.
Now in the code behind I want to move the focus to the 3rd item in the listbox.
Can somone tell me as to how can I acheive this?
I think that once we get the access to listboxItem than we can easily set the focus by calling <listboxitem>.Focus(). But now the question is how can I get a particular ListBoxItem object for a binded ListBox?

Even though it looked quite obvious to me, I didnt found a solution.

I have a problem with my TreeView in a WPF application (Framework 3.5 SP1).
It's a TreeVIew with 2 Levels of Data. I expand / collapse the items of the first level in a particular way (with a single mouse-click on the TreeViewItem). Again when I expand a first-level TreeViewItem, I add some second-level TreeViewItems to the group (it's an important detail, infact if I don't add the items the problem doesn't occur). All works good until the TreeView loses focus.
If, for example, I expand the TreeViewItem at the first position, adding at the same time one element to the second-level, then I click on a button (to let the TreeView lose the focus), and then I click again on the TreeViewItem at the third position to expand it, the TreeViewItem that results from the hit-test with the mouse position is not the "real" TreeViewItem (in this case the third), but a TreeViewItem which is in an higher position than the one clicked (in this case the second).
I have tried to use the UpdateLayout method on the TreeView-LostFocus event, but without results. Probably I need a method that does the opposite: starting from the UI, refresh the object that contains the position of the TreeViewItems.
Can you, please, help me?
Thank you!

This is the code:

' in this way I tried to put remedy at the problem, but it doesn't work.PrivateSub tvArt_LostFocus(ByVal sender AsObject, ByVal e As RoutedEventArgs) Handles tvArt.LostFocus
      e.Handled = TrueEndSub' here I expand / collapse the items of the first level of my TreeViewPrivateSub tvArt_PreviewMouseUp(ByVal sender As System.Object, ByVal e As MouseButtonEventArgs) Handles tvArt.PreviewMouseUp
      Dim p As Point = NothingDim tvi As TreeViewItem = getItemFromMousePosition(Of TreeViewItem)(p, e.OriginalSource, Me.tvArt)
      If tvi IsNothing = FalseThenIf tvi.HasItems ThenDim be As BindingExpression = BindingOperations.GetBindingExpression(tvi, TreeViewItem.ItemsSourceProperty)
          Dim ri As P_RicambiItem = DirectCast(be.DataItem, P_RicambiItem)
          If ri.isExpanded = Falsethen' here I add items to the second level collectionEndIf

          ri.isExpanded = Not ri.isExpanded
      e.Handled = TrueEndSubPrivateFunction getItemFromMousePosition(Of childItem As DependencyObject)(ByRef p As Point, ByVal sender As UIElement, _
      ByVal _item As UIElement) As childItem
      p = sender.TranslatePoint(New Point(0, 0), _item)
      Dim obj As DependencyObject = DirectCast(_item.InputHitTest(p), DependencyObject)
      While obj IsNothing = FalseAndAlsoTypeOf obj Is childItem = False
        obj = VisualTreeHelper.GetParent(obj)
      EndWhileReturnDirectCast(obj, childItem)


For some reason, all controls on my ToolWindowPane do not show standard, keyboard focus style (dashed rectangle) when they normally should (when tabbing to them). Even when applying custom FocusVisualStyle through XAML, it still does not show up. Does Visual Studio have global style that forcibly overrides this?

These focus rectangles appear correctly for internal Visual Studio tool windows, like Find in Files. Have I missed something in order to get this to work in my custom ToolWindowPane?



I have an application, say App1. From App1, I can launch a window (for convenience, let's call this window "Info Window") by right mouse clicking on a context menu item. However, the "Info Window" is not directly launched by App1 itself. Rather, App1 sends a Windows message to another application, say, App2. App2 then launch this "Info Window". My problem is that if I minimize App2 first then launch the "Info Window" from App1, the "Info Window" will come up on top of other windows but not having the focus. So you see the "Info Window" with a gray title bar and a flashing blue window button on the task bar. The focus is still on App1. I have to click on the "Info Window" to bring it to focus. HOWEVER, if I close the "Info Window" and do it again, the "Info Window" will not only come up on top but also have focus. If I click on App2 to change its state to normal then minimize it again, then the problem happens again. So basically, every time App2 changes its state from normal to minimized, the first time I launch the "Info Window" it will not have the focus.

Any idea why this is happening is welcome. Thanks in advance!



I want to set the border for a DataGrid Row which is currently having the focus. But not the seleced row because when the Multi selection is enabled for the datagrid then there is a chance that multiple rows can be selected.

I need a solution in XAML

Thanks in advance!

Please remember to click “Mark as Answer” on the post that helps you, and to click “Unmark as Answer” if a marked post does not actually answer your question. This will help other members to find the solution easily.

I have a WPF 4.0 Calendar control (Selection Mode: MultipleRange) and a button in a grid.

After selecting dates in the calendar, when I click on the button, the calendar is not losing its focus.  i.e., It leads me to click twice on the button to fire the button_click event.

Is that a known bug? I binged my level best but not finding any answer. I will appreciate if someone could solve it.

Thank you.


Hi, I'm trying to write a simple HTML editor. As a test project, the application is very simple. It hosts a single WebBrowser control in a grid.

<Window x:Class="WebBrowser.Window1"
<WebBrowser Name="WB"IsVisibleChanged="WB_IsVisibleChanged"/>  

I'd like the web browser object to have focus at all times: When the application starts and also whenever the application becomes active (by switching from another app). So I put event handlers at various locations: on Loaded, on Activated and on VisibilityChanged.

privatevoid Window_Loaded(object sender, RoutedEventArgs e)  
            IHTMLDocument2 doc2 = (IHTMLDocument2) WB.Document;  
            doc2.designMode = "On";  

Loaded is also when I switch the control to design mode.


privatevoid Window_Activated(object sender, EventArgs e)  
privatevoid WB_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)  
if (WB.IsVisible)  

First, I tried to implement SetFocus() as a call to WB.SetFocus(), but I got an System.ExecutionEngineException.
Instead, I call focus() on the browser.

privatevoid SetFocus()  
// This throws System.ExecutionEngineException
// WB.Focus();
            IHTMLDocument4 doc4 = (IHTMLDocument4)WB.Document;  
if (doc4 != null)  
                Debug.Print("focus {0}", doc4.hasFocus());  

It doesn't work. The focus is not on the editor as startup. I can click on the main window and write things, but the focus is lost when I go to another window and come back.

With SPY++, I noticed that on window activation, the SetFocus() function transfers the focus to the web browser but then it is taken back by the WPF main window.

Then I added a hook to intercept any WM_FOCUS message. It's brutal and I'd rather not do this even.

private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, refbool handled)  
constint WM_SETFOCUS = 0x0007;  
switch (msg)  
                    handled = true;  
return IntPtr.Zero;  

and added 

            HwndSource source = HwndSource.FromHwnd(new WindowInteropHelper(this).Handle);  

to Window_Loaded.

Now the focus is given to the web browser control when I switch from another app, but not at startup.

It seems like it is because SetFocus() is called before the web browser is fully materialized. SetFocus() is called but hasFocus remains false. At startup, the Debugger Output shows

focus False

When I switch from another app, I see

focus True

I tried putting several SetFocus() calls at different places during the setup but I can't make it to work.

Do you have a recommendation?



Hello guys

We have two WPF DataGrid in two TabItem when we travel between to TabItem grid did not store focused Cell  and move focused cell to first cell. Is it a true behaviour?


When I go to Passwordbox virtual keyboard gets hides on tablet.


<< Previous      Next >>

Microsoft   |   Windows   |   Visual Studio   |   Sharepoint   |   Azure