Archive

Posts Tagged ‘WPF’

ObservableObject: More goodness

March 2nd, 2011 No comments

I’ve been working my way through Karl Shiffett’s MVVM in a box training module.  He has a neat little helper for the ObservableObject that adds a check to make sure you’ve wired everything up when using string-based property changed handlers.  

 

Here is the new method:

 

/// <summary>
/// Warns the developer if this Object does not have a public property with 
/// the specified name. This method does not exist in a Release build.
/// </summary>
[Conditional("DEBUG")]
[DebuggerStepThrough]
public void VerifyPropertyName(String propertyName)
{
  // verify that the property name matches a real,
  // public, instance property on this Object.
  if ( TypeDescriptor.GetProperties(this)[propertyName] == null )
    Debug.Fail("Invalid property name: " + propertyName);
}

 

Here’s the Karl version of the entire class:

 

using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq.Expressions;

//Event Design: http://msdn.microsoft.com/en-us/library/ms229011.aspx

namespace XamDockManager.Common.Infrastructure
{

    [Serializable]
    public abstract class ObservableObject : INotifyPropertyChanged
    {

        [field: NonSerialized]
        public event PropertyChangedEventHandler PropertyChanged;

        protected void OnPropertyChanged(String propertyName)
        {
            VerifyPropertyName(propertyName);
            OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
        }

        protected void OnPropertyChanged<T>(Expression<Func<T>> propertyExpresssion)
        {
            var propertyName = PropertySupport.ExtractPropertyName(propertyExpresssion);
            OnPropertyChanged(propertyName);
        }

        protected virtual void OnPropertyChanged(PropertyChangedEventArgs e)
        {
            var handler = PropertyChanged;
            if ( handler != null )
            {
                handler(this, e);
            }
        }

        /// <summary>
        /// Warns the developer if this Object does not have a public property with
        /// the specified name. This method does not exist in a Release build.
        /// </summary>
        [Conditional("DEBUG")]
        [DebuggerStepThrough]
        public void VerifyPropertyName(String propertyName)
        {
            // verify that the property name matches a real,
            // public, instance property on this Object.
            if ( TypeDescriptor.GetProperties(this)[propertyName] == null )
            {
                Debug.Fail("Invalid property name: " + propertyName);
            }
        }
    }
}

 

You might notice, there another external requirement, PropertySupport.

Here is that class as well:

public static class PropertySupport
{
    public static String ExtractPropertyName<T>(Expression<Func<T>> propertyExpresssion)
    {
        if ( propertyExpresssion == null )
        {
            throw new ArgumentNullException("propertyExpresssion");
        }

        var memberExpression = propertyExpresssion.Body as MemberExpression;
        if ( memberExpression == null )
        {
            throw new ArgumentException("The expression is not a member access expression.", "propertyExpresssion");
        }

        var property = memberExpression.Member as PropertyInfo;
        if ( property == null )
        {
            throw new ArgumentException("The member access expression does not access a property.", "propertyExpresssion");
        }

        var getMethod = property.GetGetMethod(true);
        if ( getMethod.IsStatic )
        {
            throw new ArgumentException("The referenced property is a static property.", "propertyExpresssion");
        }

        return memberExpression.Member.Name;
    }
}

 

If you’d like more info on MVVM for WPF, check out Karl’s In the Box – MVVM Training for VS 2010.  You can get it for free.

http://karlshifflett.wordpress.com/2010/11/07/in-the-box-ndash-mvvm-training/

http://visualstudiogallery.msdn.microsoft.com/3ab5f02f-0c54-453c-b437-8e8d57eb9942?SRC=VSIDE

Null Object to Visibility Converter

February 28th, 2011 No comments

What?  Why could you possibly need that?!?

Let me explain.  I’ve got a Infragistics XamDatGrid with lots of data in it.  I’ve also got a XamChart that displays the selected row in the grid.  On start-up, nothing is selected in the datagrid so my active data item is null.

So what’s the problem?

The problem is when there is no data bound to the chart, it “helps” by showing you the default data sample.  My users find this confusing and distracting, especially when our chart type does match Infragistics choice.

So how to fix it?

I’ve seen some comments on the Infragistics forums with solutions to override this behavior.  But why bother?  Wouldn’t it be simpler to hide the chart when there is no bound data instead of writing a bunch of code to load in a default/empty data set?

Here’s my solution:

Read more…

Faking an image roll-over in WPF

January 17th, 2011 No comments

Problem:

I have an image in a button.  I’d like the image to change or toggle when the user clicks the button just like I can do with JavaScript.  You remember JavaScript…  Don’t you?  Not jQuery, but real JavaScript.  <sigh>

Anyway.  Here are a couple solutions that I worked out.     

Read more…

Rotating the text in an Expander Header

September 27th, 2010 No comments

Before I forget how…

   <Expander ExpandDirection="Left" Grid.Column="2">
     <Expander.Header>
       <Label>
         <Label.LayoutTransform>
           <RotateTransform Angle="90" />
         </Label.LayoutTransform>
         <Label.Content>
           Expander Title
         </Label.Content>
       </Label>
     </Expander.Header>
     <!—Your Content-->
   </Expander>

WPF Challenges

April 22nd, 2010 No comments

Has anyone played with the old PresentationFramework.dll themes?  I usually use the WPF Themes from CodePlex, but I wanted to see how these themes would look.  After all, why wouldn’t I want my app to look like a windows app instead of some quasi-cartoon thingy?

I know I’ve been AWOL for a while.  I’ve been busy with the business.  Monday I searched for a charity.  Tuesday, my new laptop arrived.  I was too busy working through router issues.  Wednesday, I started playing with my laptop and researching a version control solution.  TFS will not work at the office.  I ended up with a free online service.  We’ll see if it works as planned.  Today was more laptop work and adding projects to Subversion.  Tomorrow, I have another new client meeting and a laptop to fix.  My old netbook migrated to my employee.  After Tuesday’s issues he can no longer connect to the network cleanly.

Read more…

App version by the deployment method

January 10th, 2010 No comments

I have several clickonce deployments. And it gets old having to manually increament my version numbers in the AssemblyInfo file especially when my deployment method does that on it’s own.

So… Here’s my solution. Read more…

One way to manage an ‘OK’ button with WPF / MVVM

November 20th, 2009 1 comment

I am using the M-V-VM pattern on a WPF app. The rules that we are following on my team state that the View only knows about the ViewModel via the DataContext. The ViewModel has no explicit knowledge of the View.

BTW: I created the project using the WPF M-V-VM template available on CodePlex (I think?). It already contains the DelegateCommand classes.

I have an “OK” button.

In WPF, a button does nothing. If you want to do do “something” you have to wire up a command that resides in the ViewModel.

View:

<Button Command="{Binding UserClickedOkButtonCommand}" Content="OK" />

 

ViewModel:

public ICommand UserClickedOkButtonCommand { get { return new DelegateCommand( UserClickedOkButton); } }

public void UserClickedOkButton()
{
// do something
}

 

If you put a break point on the UserClickedOkButton, you will see the event is correctly mapped to the delegate method. So how do I close the View?

It takes a couple extra steps to get all of your ducks in a row.

First, add an x:Name=”ThisWindowName” to your View header.
Second, add a command parameter that refers back to your new window name.
Third, update the Command in the ViewModel to use a Window as it’s argument.
Fourth, use the input window argument to close the window.

Here’s the code.

View:

<Window
	...
	x:Name="ThisWindowName"
>
...
<Button Command="{Binding UserClickedOkButtonCommand}" CommandParameter="{Binding ElementName=ThisWindowName, Path=.}" Content="OK" />

 

ViewModel:

public ICommand UserClickedOkButtonCommand { get { return new DelegateCommand( UserClickedOkButton); } }

public void UserClickedOkButton(Window window)
{
	// Do Something
	window.Close();
}

The window is closed. Concerns are separated. MVVM rules are followed.

Works on my machine.

WPF Margins

October 21st, 2009 No comments

Setting a WPF / XAML Margin control within the designer can be done in two different ways. If you want a single value for all directions: Margin=”5″. If you would like different margins, then put a space between each assignment: Margin=”5 10 5 0″ The assignment order is left, top, right, and finally bottom.

Tags: ,

Convert Enum to String / String to Enum

October 15th, 2009 1 comment

I found this today. I need to convert an enumeration into a string list to populate a combobox. I had been looking at converters to do the heavy lifting, but realized that I should do the work in the ViewModel. That simplifies the XAML a bit. While I was typing out code to read the enum values from the settings file Resharper showed me a choice… I could use my custom converter or use the one in the Component Model. Well, I’d rather use the framework solution over a custom solution any day. If nothing else it’s less to test.

Here’s an example from MSDN:

  using System.ComponentModel;

  var myServer= Servers.Exchange;
  string myServerString = "BizTalk";
  Console.WriteLine(TypeDescriptor.GetConverter(myServer).ConvertTo(myServer, typeof(string)));
  Console.WriteLine(TypeDescriptor.GetConverter(myServer).ConvertFrom(myServerString));

Enjoy,

References:

MSDN EnumConverter Class
http://msdn.microsoft.com/en-us/library/system.componentmodel.enumconverter.aspx

Tags: , , , ,

Snoop

October 1st, 2009 No comments

I’ve been up to my eye-balls in WPF development lately. It is a bit different from ASP.Net and WinForm development. I found a utility today that helps me understand exactly what is going on with the UI: Snoop. Snoop can “see” all WPF apps running. You can examine the logical tree and even map UI elements to specific items on the UI surface. (Ctrl + Shift + Mouse-Over the UI element)

Snoop:
http://blois.us/Snoop/

Enjoy,

Ramp Up: Pt2

September 25th, 2009 No comments

I am struggling a bit with ths topic: “Ramping up.”

Wednesday, I forgot my phone, glasses, and external hard drive.

Thursday, I forgot my phone and wallet.

Today, I remembered everything but I found an issue in the latest release in the Infragistics WPF controls so I’m wallowing a bit trying to decide if I should work around the issue for the moment or plow straight through.

So I am having a bit of trouble ramping up as it were. Read more…

Fierce / Grind

May 17th, 2009 No comments

Friday:

It is a beautiful day and I stuck at the office. My progress with WPF has been notable, but I still have a lot to learn to create good apps. It is a very different way of thinking about things. All of this gets shelved next week. I need to slide back into the WinForm world and finish up a data validation screen that I had been working on weeks ago. Now, I need to rework a few things and finish it up.

My ride home from work was amazing.

Read more…

02:48

May 10th, 2009 No comments

Obviously, I’m not sleeping again. This always comes in spells. Today was a busy day. I worked on the mower, setup/assembled a fan and water cooler at the office, cleaned the gutters, hung some art, patched a bare spot in the yard, sprayed all of the weeds, blah, blah, blah… I should be tired. I didn’t nap today but I did consume 5 glasses of Pepsi. That’s probably why I’m still awake. Read more…