Jaime Rodriguez
On Windows Store apps, Windows Phone, HTML and XAML

  • Jaime Rodriguez

    high level deck on Sharing code between WPF and Silverlight

    • 2 Comments

    This week, I had the pleasure of presenting at the “Phoenix AZGroups Scott Guthrie event”  (with Scott and Glenn).

    The deck that I presented is here. It includes a small section on some of the most relevant differences between WPF and Silverlight (3); any one wanting to know the differences, should check it out.  If you have a difference you would like me to add, please email me or add a comment here.

    --
    I have to thank all the people that attended the event and our hosts Scott Cate and Joseph Guadagno. I flew down thinking it was a ‘smaller event’ (maybe 300 people) and was incredibly surprised with what they put together; it felt like a one-day conference, with ~800 people registered, great food and location, and huge give aways ( netbooks, Flip HD cams, books, etc.. ). Very, very impressed, congrats to the usergroup on such a great event.  

    PS --  I will come back to the sharing code between WPF and Silverlight topic; in preparation for the talk, I spoke to 8 companies (agencies, ISVs, enterprises, etc.) doing code sharing already; overall, they were positive.  it is not seamless, but it can definitely be done.  If you want to see the client continuum in action, check Telerik’s SalesDashboard; built with high % of shared code between WPF and Silverlight; it uses prism too].  they give out the source for it too. Nice!

  • Jaime Rodriguez

    List of features to track in WPF4 and the details on beta1

    • 15 Comments

    I am late to this  but still wanted to share an “insider view” into the status of “WPF 4” in the recently released .NET Framework 4 and VS 2010  beta1.


    Status of the run-time (on the public beta 1).
    The WPF team cranked hard until last minute on 3.5 SP1 so they have been playing catch-up to .NET 4 and VS2010.  The beta does not really do justice to the progress the team is making towards RTM. In a few cases, the team ‘compromised’ not shipping the feature in beta1 to optimize for the RTM schedule (preparing a beta does take integration work and testing, plus they had to put the longer/harder features up-front to decrease ship risks). 
    Beta2 appears to be in good shape for you to preview and share feedback still before .NET 4 RTMs.  

    For those looking into beta1, I would say the two areas where we need feedback will be:

    • The new XAML stuff (in particular we want to make sure we do not break you)
    • The tools ( Cider designer);  I would love to hear what people think of the new features. 

    Want to learn more about beta1. Here is a bit of the action:

    • Video Interview with Ian Ellison Taylor WPF and Silverlight GM, and Kevin Gjerstad, WPF Group Program Manager.  It pretty much discusses what is in and out (for beta1 and RTM).
    • Rob Relyea recorded a video on the XAML enhancements.  This is a must watch and then follow it with this post and any other recent posts in Rob’s blog.
    • Jossef Goldberg has a great post on client profile in .NET4.  We recorded a video, to be posted in the next few days; look for it here via update to this post, or in the continuum show.
    • Tomorrow we are shooting the Touch video;  ironically they reached feature complete in beta2 today, maybe we can get a peek; video should be posted early next week. 
      [If you want to know why I am posting today instead of next week, we are doing LOB Tour in NY this weekend, so I am out on the road again. I hope you understand, post will be updated as we go]
    • WindowsClient.net now has a new section for the Cider designer. Karl Shifflett and the Cider crew will be putting videos there as they go. For starters, Mark Wilson-Thomas has a good “Lap Around Cider in beta1 .  


    On the way to .NET 4.
    Here is my view into the new features I am tracking and current (best guess) estimate on timelines. The list is not all inclusive, so let me know if I missed one you cared about.  note that this list focuses on new stuff;  I did not include all the bug fixes and minor improvements to existing stuff.

    Huge WARNING!!  None of the below features are guaranteed.  Nothing is official until we RTM. 
    Please do not make assumptions or plans based on this list.

    Category

    Feature

    In beta 1

    Expected by  beta 2

    Windows 7 light-up

         
    Multi-Touch Basic manipulation and inertia.
    Raw touch events are not in.
    Yes.  Beta1 + Raw touch.  A few tiny breaking changes.
      Taskbar integration Not in beta 1 Yes
      Vista + Win7 Native Dialogs Yes Same as beta1
      Ribbon (though it is not win7 specific at all). Not in beta 1 Ribbon will be shipping out of band still.  Next preview ships after beta2. It will RTM by .NET 4 RTM or earlier.
        Graphics& Text      
      Text enhancements Not in beta 1 Yes
      Cached Composition Not in beta1 Yes
      Support for Pixel Shaders written w/ HLSL 3.0 Not in beta 1 Yes
      Caret customization Not in beta 1 Yes
      ClearTypeHint Yes Same as beta1
    Legacy effects get cut Yes. Old legacy Bitmapeffects are a no-op, unless it is one of the effects that are hardware accelerated. Same as beta1
    Fundamentals & AppModel      
      XAML 2009 Beta1 Yes, minor changes.
      LayoutRounding Not in beta1 Yes
      Bindable Run Not in beta1 Yes
      Visual State Manager Not in beta1. In by beta2, now shipping in the framework.
      Animation Easing functions Yes Same as beta 1
      Datagrid Yes. Moved from toolkit to framework.  Minor bug fixes. Same as beta 1.
    DatePicker Move from toolkit to framework. Minor fixes. Same as beta1.
      Full Trust XBAP Not in beta1 Yes
      Databinding improvements Not in beta1. Yes
         Deployment
    Client Profile New client profile is in, but no web bootstrapper. Still needs to be compressed (for size). Yes, full functionality.
      Client Profile Configurator No. Will ship out of band. No. Will ship out of band.
              Tools      
      VS2010  Cider Cider has a lot of improvements.
    Perf work is not done.
    Yes.
    VS2010 new Editor Since the text enhancements are not in the run-time, the editor does not get them. Yes.
           


    Note: At PDC, we said that DeepZoom would be in WPF4. Unfortunately that feature has been cut. We just could not squeeze it into the schedule.  There are workarounds to it: you can host Silverlight inWPF using web browser control or using the Silverlight hosting APIs.
     

    Details on  the features:
    Below are high level descriptions around the features listed above. Must share that Ted Hu created the descriptions for a different document and I am shamelessly plagiarizing it. Thanks Ted.

    Multi-touch
    Windows 7 is introducing multi-touch input and manipulation processing, which Windows Presentation Foundation exposes. Multiple finger input will be exposed through existing and new input events, while new manipulation and inertia events will be exposed for developers to consume.

    • Multi-touch Manipulation and Inertia (Pan, Zoom, Rotate) events on UIElement
    • Raw Multi-touch events (Up, Move, Down) on UIElement, UIElement3D and ContentElement
    • Multiple capture supporting multiple active controls
    • ScrollViewer enhancement to support multi-touch pannning
    • Touch device extensibility
    • Future Surface SDK compatibility

    Windows 7 Shell Integration
    WPF 4 exposes several new Windows 7 Shell features to WPF developers These Shell features empower application authors to provide a richer, integrated user experience. The new taskbar is less cluttered and can convey more information at a glance. The Aero thumbnails support user commands. Jump lists provide access to contextual startup tasks and files available to the application.
    WPF 4 will integrate Windows 7 JumpList functionality, including:

    • Tasks
    • Items
    • Recent and Frequent Lists integration
    • Custom Categories

    Taskbar integration including:

    • Progress bar
    • Overlay Icon
    • Thumbnail buttons with commanding support
    • Description Text
    • DWM Thumbnail clipping

    Text enhancements
    WPF 4.0 Beta 2 introduces a new text rendering stack which allows for much clearer text rendering.  This change adds the necessary knobs to allow WPF text to look virtually indistinguishable from Windows’ traditional GDI-rendered text.  The clarity improvements also dramatically improve readability for many East Asian languages.

     

     


    ClearType hint
    ClearTypeHint allows app authors to enable cleartype when rendering text to IntermediateRenderTargets, where it would normally be disabled by the system.  The system normally disables cleartype on IRTs because Cleartype only works properly when it’s rendered to an opaque surface, and it’s extremely difficult for the system to determine if an IRT will be rendered with transparency.  By Setting this to true, you’re basically letting the system know that the IRT is transparent.  This means you can now enable cleartype with layered windows, in Visual/Drawing brushes, in Effects, and in 3D if you so desired it. 

    Full-Trust XBAP
    Starting in WPF 4.0, the ClickOnce elevation prompt is enabled for XAML Browser Applications (XBAPs) in Intranet and Trusted Zones, making it easier to deploy full-trust XBAPs. For XBAPs that require security permissions greater than the minimum code access security (CAS) permission grantset of the Intranet and Trusted Zones, the user will be able to click 'Run' on the ClickOnce elevation prompt when they navigate to the XBAP to allow the XBAP to run with the requested permissions.

    LayoutRounding
    WPF 4.0 will adopt the LayoutRounding property, originally introduced in Silverlight2. WPF’s layout engine frequently calculates sub-pixel positioning coordinates. This can lead to rendering artifacts as elements positioned on sub-pixel boundaries are antialiased over multiple physical pixels. LayoutRounding will force the layout engine to place elements on whole pixel boundaries, thus removing most of the rendering artifacts caused by this problem.

    Bindable Run
    The Run class has had a simple CLR property Text since the first release of the framework. In WPF 4.0 we have backed Run.Text with a dependency property. Among the many benefits of being a DP, Run.Text now supports data binding. One-way binding (from data source to Run.Text) is fully supported, and two-way binding is supported as long as the Run is not modified via the Text OM or from a RichTextBox.

    Selection and caret customization
    Simple app customization is a great WPF strength. In the past, the selection color and caret color for text input and reading controls (TextBox, RichTextBox, FlowDocumentReader, etc...) has been hard coded. WPF 4.0 will introduce the SelectionBrush and CaretBrush properties. These properties will allow developers to control the brush used to draw both selection and carets in many WPF controls.

    Animation Easing functions
    Is the exact same functions we announced in Silverlight 3;  I can not tell you who created them first; funny how schedules work; but really nice to have compatibility.

    BindingExpressionBase.ValidateWithoutUpdate does for a single binding expression what BindingGroup.ValidateWithoutUpdate does for a binding group – namely it starts the validate/update process but stops just before writing a value back to the source item

    When BindingGroup.SharesProposedValues is true, the binding group will keep track of proposed values even when the UI elements that hold them are replaced.  This supports a UI design pattern used by DataGrid (for example), where only one source property is presented with an “editing template” (containing editable controls – TextBox) while the other properties are presented with “display templates” (containing non-editable controls – TextBlock).   As the user focuses a new property, its display template is replaced by an editing template, while the previously focused property’s editing template is replaced by a display template.  The BindingGroup now manages the proposed value (if any) held by the old editing template, so that it can be displayed (if possible) in the display template and written back to the source when the user commits the binding group

    LayoutRounding
    Speaks for the feature already in Silverlight, where the layout system rounds any non-integral values at the time of a layout pass. This helps prevent the sub-pixel anti-aliasing effects that people describe as "blurriness"

  • Jaime Rodriguez

    WPF Discussion, 090522

    • 1 Comments

    I hope you remember the drill; sorry that I missed last week, we had school


    Subject: ItemsControl and Screen Reader

    I have a WPF 4.0 ItemsControl as follows. The AutomationProperties.Name attached property is set to a string for the item containers. I expected the screen reader to read out the string when the item container get focus, however screen reader (I am using Narrator) actually read nothing. Could anyone give me some insights? Is it a bug of my code or the screen reader or WPF? Thanks a lot!

    Answer:
    Unfortunately ItemsControl does not support UIAutomation – it is primarily intended to be used as a base upon which multi item controls are built.
    You could switch to any of the ItemsControl subclasses that do support UIAutomation (ListBox is probably your best bet)
    Alternatively you can override OnCreateAutomationPeer in your own ItemsControl subclass and return an AutomationPeer implementation of your own. The ListBoxAutomationPeer and ListBoxItemAutomationPeer implementations are really small simple starting points.


    Subject: Create hidden WPF window ... with an HWND

    I am trying to create a WPF Window that’s initially hidden, do a bunch of initialization, then show the window. In my case the initialization requires access to the HWND that will be hosting the Window. But it appears to me that the HWND is not actually created by WPF until either I call either Window.Show() or Window.Visisibility=Visible. And doing so, of course, makes my app window visible but blank for awhile before my initialization is complete.

    Answer:
    Currently, the only good workaround here is to supply an initial window position that’s entirely off-screen, then move it into view once everything’s ready.  That way the blankness/flicker can’t be seen.  For our next release, we’ve added a method to the WindowInteropHelper class called EnsureHandle to cause the HWND to be created before the window is shown.


    Subject: Rendering delay when first displaying cached images

    I’m tracking down a perf issue with my WPF application. Basically I cache a BitmapImage:

    this.cachedImage = new BitmapImage();

    this.cachedImage.BeginInit();

    this.cachedImage.CacheOption = BitmapCacheOption.OnLoad;

    this.cachedImage.UriSource = new Uri("IMG_0726.JPG", UriKind.Relative);

    this.cachedImage.EndInit();

    Then later I go to show it with

    this.imageElement.Source = this.cachedImage;

    But with large images, there is still a significant delay before the image renders, of a second or two. The UI thread does not appear to be blocked during this delay, so I suspect some conversion is happening on the render thread.

    Answer:

    Answer 1
    We take a hit downsampling to display size - if you set DecodePixelWidth/Height on your bitmap to your display size, does that make this issue go away?

    Follow-up 1 --

    Though I do see a significant delay when resizing by a large margin, so that could be part of it. I still see a (smaller) delay when displaying an image with DecodePixelWidth set to the display size.

    Answer 2
    Right – we use high-quality resampling down to w/in sqrt(2) of the display dimensions, so you have to double (or halve) the area to cause us to do the “good” resampling. 

    As an alternative, if the image quality is acceptable to you, you can set RenderOptions.SetBitmapScalingMode on the element displaying the Bitmap to speed this up.

    http://msdn.microsoft.com/en-us/library/system.windows.media.renderoptions.setbitmapscalingmode.aspx

    Follow-up

    Thanks for the tip! Resizing to any size is now basically instant and looks pretty good.



    Subject: TranslateTransform+ScaleTransform wierdness (artifacts)

    I am seeing a weird problem when I applied TranslateTransform+ScaleTransform on a group of elements. When I change the scale factor, there is this random/unexpected gap between elements where they should be near each other.

    Answer:

    While the UI thread uses double precision for layout/hit testing, the rendering thread that actually displays everything converts all values to single precision floating point for speed. I haven’t run the numbers to determine if you’re outside the threshold of precision, but I would suspect that given your symptoms you might be.


    Subject: RE: when do property changed event delegates get hooked up?

    <Skipped question>

    Answer:

    A1
    Correct – setting the Filter property (on a view) will cause that view to refresh.  Setting some other property, such as a property on the data item that the filter might read, does not cause the view to refresh.  Nor does it cause the item to be “re-filtered”.

    The doc says that setting Filter (or Sort or Group) causes a refresh (meaning an immediate refresh).    It’s not meant to imply that you never need to call Refresh ever again.

    A2

    I would argue the most straight forward reading of that MSDN fragment is that Refresh happens automagically.  I know (from experience) that this isn't true for Filters (and can't be true), but it is true for Sorting and Grouping iirc.  I think making it more explicit (i.e. SETTING Filter will cause a refresh) couldn't hurt.


    A3
    It is not true for sorting and grouping.  Like filter, it is true that adding/removing a SortDescription or GroupDescription causes an immediate refresh, but changing a property on a data item (such as one that participates in the sorting or grouping) does not cause a refresh, or even a “re-sort” or “re-group”.


    Subject: Any easy way to save a FlowDocument into a rtf or htm file?

    Answer:

    You can use TextRange.Save() with DataFormats.Rtf. You can get the TextRange with: 
        new TextRange(flowDocument.ContentStart, flowDocument.ContentEnd);

    Answer 2:
    The RTF converter doesn’t know what to do with embedded UIElements, so embedded TextBlocks will be dropped.

    Followup2: Need data binding; that is why textblocks.

    Answer 3:
    We’ve made Run.Text a DependencyProperty for v4, so if you can build off of netfx4 databinding is supported directly.  Otherwise, for earlier version of the framework see
    http://fortes.com/2007/03/bindablerun/.

    Follow-up3:
    will TextRange.Save support save to html format in .net 4.0 ?

    Answer 4:
    Unfortunately TextRange.Save does not support html in any version.


    Subject: async bindings

    Are async bindings evaluated on a background thread? 
    Answer:
    Yes!


    A Rob Relyea must read ( I will come back to WPF in .NET 4 this weekend ).
    http://blogs.windowsclient.net/rob_relyea/archive/2009/05/19/xaml2009-and-system-xaml-dll-preview-in-net-fx-4-beta1.aspx


    Subject: Crash in wpfgfx_v0300

    We have a small application that makes extensive use of DoubleAnimations to constantly move things around the screen. The way the code is currently written the animations are created and destroyed on a regular basis. application sometimes crashes in wpfgfx_v0300.

    Answer:
    http://support.microsoft.com/kb/962231


    Subject: creating animated gifs using WPF

    Answer:
    In Win7, WIC supports GIF metadata and you can do this in WPF natively.


    Public Announcement from Eric Fabricant

    Subject: Update available for the .NET Framework Assistant for Firefox

    Included in the .NET Framework 3.5 SP1 is an extension for Mozilla Firefox that adds ClickOnce support and reports installed versions of the Framework to a web server. This initial release didn’t provide a means of servicing the extension out-of-band without depending on Mozilla and was installed as a machine level component which prevented users from uninstalling the extension.  To remedy these issues the Update to .NET Framework 3.5 SP1 for the .NET Framework Assistant 1.0 for Firefox has been released, updating the extension to version 1.1.

    Grab your copy today before Firefox 3.5 introduces changes that will break version 1.0 of the extension and render it disabled.

    Note: This issue has already been addressed in Windows 7


    Subject: RE: Creating image from browser

    Can I use GetDrawing() to obtain a snapshot of the FrameworkElement returned from another AppDomain via the CLR AddIn model.  The HwndHost control looks like an instance of MS.Internal.Controls.AddInHost.  I’ve adapted the code below but I’m still receiving a blank image.  Is there something different about the CLR AddIn model that would prevent this from working?

    Answer:

    What’s blocking your attempt is this in AddInHost:

    /// <summary>

    ///     GetDrawing - Returns the drawing content of this Visual.

    /// </summary>

    internal override DrawingGroup GetDrawing()

       {

    // HwndHost.GetDrawing returns a bitmap by calling the PrintWindow win32 API.

    // This logic fails for the WPF hosting WPF (HwndHost + HwndSource) scenario.

    // It currently works this way: PrintWindow redirects to Paint; If it is WPF,

    // it calls back into HwndTarget.DoPaint, which invalidates window region.

    // However, mil repaints async. Mil might not start paint before print.

    // That is why it prints black(bug 117011).

    //

    // In 3.5 we decide to override HwndHost behavior and return null for hosting WPF, which will print white.

    // So we do not waste toner printing black.

    // There are a couple of approaches we will investigate in the future release

    // 1. API that prints other than PrintWindow (This enables all WPF hosting WPF scenario).

    // 2. The host communicates with the add-in via contract, HwndHost GetDrawing calls HwndSource.RootVisual.GetDrawing.

    //    (This is add-in specific).

    if (_addInHwndSourceWrapper != null)

           {

    return null;

           }

    else

            {

    return base.GetDrawing();

           }

       }

    So, you have to get to the add-in’s Visual in its AppDomain, and call GetDrawing() on it directly.

  • Jaime Rodriguez

    Thank you London. here is the content

    • 4 Comments

    Our second stop in the “WPF for Line Of Business Tour”  was London, last week.  londonxamlized

    We had a full-house with people from Germany, Italy, France,  Poland, Switzerland, Spain, United Kingdom, and probably other countries. 

    The content evolved (a small %) from the LA training:
    Updated decks;  Updated demos
     
    London attendees, THANKS for joining us!!  It was a pleasure!
    New York,  Chicago, & Phoenix get ready!  

    PS.- While in London, we also got to xamlize with WPF disciples Marlon Grech and Sacha Barber.  I had not met them in person before, but I can now confirm: their passion and knowledge on WPF and .NET is as good as you read on their blogs.  Cheers!

  • Jaime Rodriguez

    WPF discussion, 090501

    • 2 Comments

    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.

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

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

                    MyDataGrid.UnSelectAll();

    }

    else {

                    MyDataGrid.UnSelectAllCells();

    }


    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?

    Answer:
    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?

    Answer:
    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?

    Answer:
    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.

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


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

    Answer:
    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;
    why??

    Answer:
    Order matters. must style first ..

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


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

    Answer:
    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?

    Answer:
    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

    Answer:
    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?

    Answer:
    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()

               {

                    InitializeComponent();

                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);

            [DllImport("user32.dll")]

            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.

    Answer:
    Try Window.Owner.  http://msdn.microsoft.com/en-us/library/system.windows.window.owner.aspx
    Setting
    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

    Answer:
    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?

    Answer:
    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?

    Answer:
    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.

    Answer:
    http://social.msdn.microsoft.com/forums/en-US/wpf/thread/28b4357a-1d9d-4af3-8fe5-87f1b01fe150/ 


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

    Answer:
    http://blogs.msdn.com/unnir/archive/2009/03/27/a-sample-that-shows-the-new-blend-design-surface-extensibility.aspx
    http://blogs.msdn.com/unnir/archive/2009/03/22/writing-a-design-time-experience-for-a-silverlight-control.aspx


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

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


Page 1 of 1 (5 items)