Archive for category WPF

How to handle action on enter key press in textbox in WPF

Did you want your OK button or your commit action to take place when you hit enter in a text field in a WPF dialog? You may have implemented a Find dialog, or maybe you have a one field text entry and you want the Enter key to commit the action.

Well, its actually really easy once you learn the simple trick to wiring up the commands.

I have a command called SaveProcessCommand on my viewmodel. I have it wired to my dialogs “OK” button. I also wanted the user to just hit Enter when they were done typing, since that is how my usability study determined users expect.

Enter the simple InputBinding. Pretty cool.

  <TextBox Margin="10,0,0,0" HorizontalAlignment="Stretch" Text="{Binding Name, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Grid.Column="1">
                 <TextBox.InputBindings>
                    <KeyBinding Command="{Binding SaveProcessCommand}" Key="Enter"/>
                 </TextBox.InputBindings>
 </TextBox>

I have the binding to the property update on each keystroke, so it is always up to date. The InputBinding then wires up the Enter key to a command. The command can do whatever you want, you are using MVVM right? Happy Coding!

, , , , ,

No Comments

How to reclassify your project into a WPF project in Visual Studio

Are you looking to change your project from a normal C# class library to a Window Presentation Framework project?

Well, it is not that hard once you learn the trick. It took me a little while to dig up the info, so hopefully this saves you some time.

Open your csproj file in notepad. Look for the ProjectTypeGuids key. If not found, add it.

Here is what it should look like when your done.

<ProjectTypeGuids>{60DC8134-EBA5-43B8-BCC9-BB4BC16C2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>

Visual Studio 2012 and Visual Studio 2010 use these to identify the project type. The settings above make it a C# WPF app.

Example:

SNAGHTML77868191

 

Happy Coding!

, , , ,

No Comments

How to get command line args in WPF?

Are you looking how to get the command line arguments in WPF?

It is actually really easy. Simple call Environment.GetCommandLineArgs()

You will be returned a string array (string[]). Remember, the first value is that of the exe being called. i.e your app.

 

   Environment.GetCommandLineArgs() 

Happy Coding!

, , ,

No Comments

How to handle keypress in WPF using MVVM?

Did you want to capture the Enter key on a textbox, or the F3 key for find again in your WPF Application when you are using MVVM?

I was using custom behaviors for a while until I realized I was overcomplicating things far too much.

You can wire up commands right to keys very easily.

Here is a sample. Same concept for any framework control.

 <Window.InputBindings>         
         <KeyBinding Command="{Binding FindNextCommand}" Key="F3"/>
 </Window.InputBindings>
 

If you had a textbox, just set the TextBox.InputBindings and the key to Enter. Happy Coding!

, , , , , ,

No Comments

Looking for a TreeListView for WPF?

I recommend taking a look at a great new .NET WPF control for TreeListView data. i.e Hierarchical data in a ListView form.

Here is the link to it. Works great and performs blazing fast. WPF TreeListView

, ,

No Comments

How do I bring to front a WPF Window?

If you are a WinForms, Visual Basic, or basically a programmer from a past generation, then you are wondering where the heck the BringToFront method is. Yes, we could invoke API’s on the window handle (that was the norm when I started programming Windows, DOS was so much easier). Anyway, WPF likes to do things with highly unobvious naming.

So, if you want your WPF window to come to the front, apparently you now Activate it. Yup. I preferred the BringToFront way more.

Anyway, Activate works fine.

var window = new YourWindowClass();

window.Show();

……

//Sometime later it is behind your main app for whatever reason, user put it there, but you now you want it in front.

window.Activate();

 

My use is I have a singleton window that gets shown and hidden, but if it is shown and not in front, I want it brought to front so the user doesn’t get confused.

Simple function, been since Windows could overlay, but in WPF you get a new methodology for invoking it.

 

Happy coding!

, , ,

No Comments

How to set TargetNullValue in a WPF Binding to an empty string when the item is NULL.

You can just set the TargetNullValue to an empty string using a Static.

 <TextBox MinWidth="30" 
Text="{Binding StepRefNo,
             TargetNullValue={x:Static System:String.Empty} }" 
/>

Be sure to add this to your class def at top.
xmlns:System=”clr-namespace:System;assembly=mscorlib”

Happpy coding!

, , , ,

2 Comments

Death by icon: Memory Leak in WPF Using MVVM and ImageSource

I was running a memory profile on our client application and kept seeing views being stuck in memory. It was odd since we freed them and there weren’t any discernable links that should be keeping them alive.

Well, that is until I saw that a GC Root object holding a reference at the top of the chain was an icon. An Icon. It was holding together a massive view and all the data, controls and containers that go with it. The memory would increase by 5-10 megs each time you went and left the view.

So, my next step was to figure out how in the world this icon was holding the view in memory. Where was the reference? The only usage was a simple binding to show the icon for particular types of nodes in our treeview.

I remembered from an earlier performance run that WPF has Freezable objects. WPF monitors these objects for changes. Well, that sounds like it uses an event. I doubt it polls.

I was right. There is an event on the image source. Apparently WPF latches on to that bad boy, and voila. You have a valid reference to the icon that the GC see as needed.

Why needed, well, to save cycles, we use a static instantiation of the bitmap. Loading from resources is expensive, so we use a readonly static. It never goes anywhere, therefore anything bound to its events doesn’t go anywhere.

So, what is the fix? I don’t want to stop using my static, as now I introduce a performance penalty. I can’t stop using the icon, then the user would be perturbed.

What to do?

Well, bring out your ice ray gun, because the solution is to Freeze the image. I mentioned earlier that WPF has Freezable objects. Well, if you Freeze it, then WPF doesn’t bind to the event since the object can’t change. So, a few lines of code later and we have a memory leak disaster averted.

Here was the old way:

private static readonly ImageSource MyIcon = new BitmapImage(new Uri(&quot;pack://application:,,,/Seekford.Client.Resources;component/Images/Icon.png&quot;)); 

Here is the new way:

   private static readonly ImageSource MyIcon;
        static MyTreeModel()
        {
            MyIcon = new BitmapImage(new Uri(&quot;pack://application:,,,/Seekford.Client.Resources;component/Images/Icon.png&quot;));        
            PARRiskIcon.Freeze();           
        }

Simple, right. Yeah, if you know what to look for in the first place Smile

 

Happy coding!

, , ,

No Comments

WPF IValueConverter Culture isn’t what you expect

I came across a defect that our DateTime IValueConverter wasn’t showing the local users regional settings.

I set a breakpoint into the converter and looked at the culture variable being passed in. The ShortDateFormat was "M/d/yyyy".

Well, my regional was set to "dd-MMMM-yy"

What gives?

I checked CultureInfo.CurrentUICulture. It had the right format string.

I attempted the language override fix:

  //Defaulting WPF to use at least the current cultures default values. Converters will still not use the local UI culture by default...
                FrameworkElement.LanguageProperty.OverrideMetadata(
                        typeof(FrameworkElement),
                        new FrameworkPropertyMetadata(
                        System.Windows.Markup.XmlLanguage.GetLanguage(CultureInfo.CurrentUICulture.IetfLanguageTag)));

Didn’t help with my scenario at all.

So, in the end, I just used CultureInfo.CurrentUICulture to format the string. A bit annoying.

 public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (value == null) return NoDateString;
            var d = value as DateTime?;

            if (d.HasValue) return d.Value.ToString(parameter.ToString(),System.Globalization.CultureInfo.CurrentUICulture);
            return value.ToString();
        }

If you find a better way, please feel to drop me a note.

Happy coding!

, , , ,

No Comments

Perforator doesn’t allow me to attach to any processes

Are you using the WPF Perforator in the WPF Performance suite and wondering why the process attach dialog has everything greyed out and disabled?

So did I. It drove me nuts, until I found out one key thing. Apparently, Perforator can only attach to processes that were started AFTER the Perforator tool was.

Gee…Wouldn’t that have been a nice thing to show in the dialog as a hint? Apparently, no one writing that tool thought about the UX in that scenario. Showing them greyed out, brilliant.  A tooltip, message, anything that said "This process can not be attached to because it was started before Perforator" would have saved serious time.

Hopefully this little nugget will save you time as well.

So, how do you attach Perforator to a running process? Start Perforator first,start your process next, then attach. Simple, yes. Intuitive, no.

Of course, you are coding in WPF. Did you expect anything to make sense?

Happy Coding!

, , , , ,

No Comments