Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change "ToString" for a sealed class

I have a class I am working with:

public sealed class WorkItemType

It's ToString is weak (Just shows Microsoft.TeamFoundation.WorkItemTracking.Client.WorkItemType).

Is there any way to override this to show the name of the WorkItemType?

Normally I would just aggregate the value in a new class, but I am using this for bindings in WPF (I want to have a list of WorkItemTypes in a combo box and assign the selected value to a bound WorkItemType variable.)

I think I am out of luck here, but I thought I would ask.

like image 644
Vaccano Avatar asked Jan 22 '10 22:01

Vaccano


3 Answers

A fairly neat way to do it might be to add an extenesion method to the WorkItemType object. Something like this:

public static class ToStringExtension
    {
        public static string MyToString(this WorkItemType w)
        {
           return "Some Stuff"
        }
    }

Then you could call something like

WorkItemType w = new WorkItemType;
Debug.WriteLine(w.MyToString();)
like image 189
SciFi Avatar answered Nov 19 '22 02:11

SciFi


Do you need to override ToString? If you are in control of the code where the object is displayed, you can always provide a FormatWorkItemType method, or something to that effect.

like image 34
Dan Tao Avatar answered Nov 19 '22 03:11

Dan Tao


WPF provides a few different built-in ways to do this right in the UI. Two I'd recommend:

  • You can use ComboBox's DisplayMemberPath to display a single property value but still select from the WorkItemType objects.
  • If you want to display a composite of a few properties you can change the ComboBox's ItemTemplate to make it look pretty much however you want - formatting text, adding borders, colors, etc. You can even set up the DataTemplate to automatically be applied to any WorkItemType object that gets bound anywhere in your UI (same basic effect from UI perspective as changing ToString) by putting it into Resources and giving it only a DataType with no x:Key.
like image 2
John Bowen Avatar answered Nov 19 '22 04:11

John Bowen