WPF discussion, 090501

You know the drill. Raw/unedited conversations from our internal discussions. 

Subject: Datagrid SelectedIndex = -1 not working

I am using the toolkit Datagrid. When i delete a row from the datagrid, i dont want anything to be selected. Hence i am setting it's SelectedIndex to -1. But it is not working. The first row gets selected everytime a row is deleted.

SelectedIndex = -1 works only when DataGrid.SelectionUnit is FullRow. The following code should work…

if(MyDataGrid.SelectionUnit == DataGridSelectionUnit.FullRow) {



else {



Subject: Can I set WPF title bar color programatically?

In Vista with Windows Vista theme, I can change the title bar color by changing the window color in “Control Panel -> Appearance and Personalization -> Window Color and Appearance”. I wonder if I can change the title bar color in my code instead of changing the window color?

There are no wpf specific api's to set the Windows Theme settings; Wpf will pick up the setting and respect them but not the other way around.  Using   uxtheme.dll and some pinvokes it might should be possible to change the look of the title bar for your application or the computer. Try:
http://pinvoke.net/default.aspx/uxtheme.SetSystemVisualStyle and http://www.codeguru.com/vb/gen/vb_misc/gamesandfun/print.php/c14319__6/

Subject: Clipping a Bitmap in memory

Is there a way to clip an image only “in memory”? I’m looking for a technique similar to the code-only approach used with TransformedBitmap?

Try CroppedBitmap

Subject: Default Style

I have a custom control based on an Expander that has an additional boolean property.  Is there a way to write a style for my controls such that when my property is false I return whatever the default style for the Expander is and if it is true I return my own variation?

We have a protected DefaultStyleKey property that is used to query the Default Style for a control. Since you are subclassing the Expander control, you could listen for changes to your new custom Boolean property and change the DefaultStyleKey property in accordance. i.e when your property is false the DefaultStyleKey should be typeof(Expander) and when it is true it should probably be typeof(MyCustomExpander). This will cause your control to automatically pick up the right DefaultStyle in these two cases.

Subject: finding relative positions

I am having an issue finding relative positions of elements inside of their containers. If an element is automatically aligned (or placed without specific positions) there doesn’t seem to be a way to find its relative position to its parent, which I think should be something that is be available on all elements and am curious as to why this is not accessible.

Try Visual.TransformToAncestor(Visual ancestor), passing in the parent as “ancestor”?

Subject: Coercion on inherited context
Thread is too long, sharing the conclusion though.

Coercion on inherited context is broken; there is a bug for this

Subject: Full screen window.

This works:   <Window Topmost="True" WindowState="Maximized" WindowStyle="None" … >  but this does not : this.WindowState = WindowState.Maximized;  this.WindowStyle = WindowStyle.None;   this.Topmost = true;

Order matters. must style first ..

this.WindowStyle = WindowStyle.None;
this.WindowState = WindowState.Maximized;
this.Topmost = true;

Subject: Guidance redistributing Microsoft.Expression.Interactivity.dll?

Because there is no Go-Live license associated with Blend 3, please do not redistribute these components publically outside of sample code. When Blend 3 RTMs, we will be releasing an SDK that includes, among other things, the Behaviors runtimes. Do note that you will be responsible for servicing your application with any updates we provide to the behaviors, etc.


Subject: hittest and ishittestvisible.

I’m setting a user control as IsHitTestVisible=false; but the VisualTreeHelper.HitTest still be able to hit itself or its children.
Is there a hittest function that I can call to not to hit the user control and its children when such flag is set?

You should be able to use UIElement.InputHitTest to work-around this behavior.
Note that even then, it will be hit testable, it’ll just be considered  part of the parent in terms of where the event is raised, etc.  That is, this doesn’t make an element “transparent” to hit test.

Subject: How to add attribute to App.Main when it is in generated code (App.g.cs)?

I would like to add the LoaderOptimization attribute to my WPF Application’s Main function but that is being generated automatically in App.g.cs by the App.xaml compilation

The easiest way:
1. Open the generated App.g.cs, take the Main() method, copy it to your code, and customize as you need.
2. Change the Build Action of your App.xaml from ApplicationDefinition to Page. (It’s not a “page” in the common sense of the word, but this is the generic XAML compilation task, which enables having code-behind.)

Subject: HwndHost loses track of focus when keyboard used

I have a customer who has a WPF application hosting native windows via HwndHost.
They expect that if the focus is on a control in their native window, they switch to another application, and then switch back then the focus will remain on their native control.  This is the behavior they get if the focus is on a WPF TextBox when the foreground application changes, and this is the behavior they get if the focus is set onto their native control with the mouse and there is no keyboard input; however, if there is any keyboard input then the focus ends up on the parent WPF window rather than on their native control.

The problem appears to be that the focus should be reset when HwndKeyboardInputProvider.FilterMessage handles the WM_SETFOCUS sent to the top-level WPF window; however, the _active flag gets out of sync if there is keyboard input.  If it is true the HwndKeyboardInputProvider thinks the window was already active and so doesn't forward the focus to the child window.  In both cases, _active is set to false when FilterMessage handles WM_KILLFOCUS as the focus moves to the native child.   If there is any keyboard input, HwndKeyboardInputProvider.ProcessKeyAction calls ReportInput which sets _active to true.

It looks like there are several known issues around this area, but I'm not sure if they cover this or not.  Does anybody know if this is already known (and if so, which bug number?)

We can work around the problem by subclassing the top level window and tracking the activation and focus ourselves, but there already appear to be several subclass methods poking their fingers into this area and I'm concerned they might conflict.  Am I just being paranoid?  Is there a better way around this?

We know how the logic in HwndKeyboardInputProvider is broken. Opened a bug for it.
There’s probably no great workaround in general, but for a specific application this may work: Preview input from our ComponentDispatcher (assuming WPF is running the message loop) and if the currently focused window is a child one, dispatch keyboard input messages straight to it. The snippet below does this. The most major side effect is that you lose access to accelerators in the main window. But if that’s an issue for the particular application, it’s probably resolvable: Get the HwndSource of the containing window and call IKeboardInputSink.OnMnemonic() on it.

     public partial class Window1 : System.Windows.Window


           public Window1()



            ComponentDispatcher.ThreadPreprocessMessage += new ThreadMessageEventHandler(OnComponentDispatcherPreprocessMessage);


        void OnComponentDispatcherPreprocessMessage(ref MSG msg, ref bool handled)


            if (msg.message >= Win32.WM_KEYFIRST && msg.message <= Win32.WM_KEYLAST)


                IKeyboardInputSink sink = _hwndHost1;

                if (sink.HasFocusWithin())


                    Win32.TranslateMessage(ref msg);

                    Win32.DispatchMessage(ref msg);

                    handled = true;





    static class Win32


        [DllImport("user32.dll", ExactSpelling=true)]

        public static extern bool TranslateMessage([In, Out] ref MSG msg);


        public static extern IntPtr DispatchMessage([In] ref MSG msg);

        public const int

            WM_KEYFIRST = 0x0100,

            WM_KEYDOWN = 0x0100,

            WM_KEYUP = 0x0101,

            WM_CHAR = 0x0102,

            WM_SYSKEYDOWN = 0x0104,

            WM_SYSKEYUP = 0x0105,

            WM_KEYLAST = 0x0108;



Subject: Managing Z-Order of Topmost windows in WPF

I have an application where I have several popup windows that I use to display information to the user. My problem is that I want to be able to programmatically control the z order of these windows so that they overlap in a way I can control.

Try Window.Owner.  http://msdn.microsoft.com/en-us/library/system.windows.window.owner.aspx
an owner window can help you predefine the Z order. If you need finer control, you can call the native SetWindowPos() function. Typical flags to pass for this purpose are SWP_NOSIZE| SWP_NOMOVE, possibly also SWP_NOACTIVATE.

Subject: Memory leak in SplashScreen

There isn’t really a good work around for 3.5 SP1 other than implementing your own splash screen instead of using the built in one.  We’ve published a blog entry with sample code here that you can use: http://blogs.msdn.com/jgoldb/archive/2007/12/10/splash-screen-to-improve-wpf-application-perceived-cold-startup-performance.aspx.

Subject: TextBox selection color

It seems from searching the web that there is no way to customize the color of selected text in a WPF TextBox control. Is this true, and is there any workaround?

This will be fixed in WPF4.  No easy workaround interim.  If you want to know the details:

Subject: Loading a resource for an app and for a referenced assembly

We have an API in our app that loads a resource.  We use this URI pack://application:,,,/Resources/icon_back_arrow.png and everything works just fine when using the application directly.

Now we’ve written some tests for this API which load our app as a referenced assembly.  The resource is not being found and I’m pretty sure it’s because of the pack URI.

I’ve found I can fix the problem if I use this URI pack://application:,,,/seahorse;component/Resources/icon_back_arrow.png  but it seems weird to me that to use resources programmatically I need to encode the name of the assembly into URIs for resources.

Is there a way of loading resources in code that will work both in the application and referenced assembly case?

Set Application.ResourceAssembly

Subject: Is there any way to let a child class automatically pick up its base class's style

I have a Control class ChildFoo defined as a subclass of control class Foo. And I defined a style with TargetType=”{x:Type Foo}”;The problem here is: I wish the ChildFoo control can automatically pick up the style defined for Foo.


Subject: Unni is blogging again. Nice posts of Blend extensibility.


Subject: Updating all bindings for an object
How can I update all bindings for an object?  With out firing propertyChanged for each property?

Raise  PropertyChanged with “”  as the propertyname (e.g. PropertyChanged (this, new PropertyChangedEventArgs(“”))  ;

Comments (2)

  1. joewood says:

    Thanks Jaime

    Do you have the ladybug link for "Coercion on inherited context"?

Skip to main content