UserControl as an interface, but visible in the Designer - c#

So we have a C# WinForms project with a Form that contains a bazillion UserControls. Each UserControl naturally exposes all the UserControl methods, properties, etc. in addition to its own specific members.
I've been thinking that one way to reduce the complexity of dealing with these UserControls is to access them through an interface. So instead of drag-and-drop to put the UserControl on the form, something like this in the constructor:
public class MyGiantForm
{
ICustomerName cName;
public MyForm()
{
InitializeComponent();
var uc = new SomeCustomerNameUserControl();
this.Controls.Add(uc);
cName = uc;
}
}
SomeCustomerNameUserControl implements ICustomerName, naturally, and ICustomerName contains the specific properties I really care about (say, FirstName and LastName). In this way I can refer to the UserControl through the cName member and, instead of being bowled over by all the UserControl members, I get only those in ICustomerName.
All well and good, but the problem is that if I do it this way, I can't see SomeCustomerNameUserControl in the Designer. Does anybody know I way I can do this but still see the UserControl on the form's design surface?
EDIT: One way to do this, which isn't overly complicated, is to put the controls on a base form. By default (in C#) the control members are private. Then I create a property for each control exposing it through the interface.
However, I'd be interested in some other way to do this, even if it's more complex. There seems to be some way to do it with IDesignerHost, but I can't find any applicable examples.

If SomeCustomerNameUserControl is defined like this:
class SomeCustomerNameUserControl : UserControl, ICustomerName
{
}
You can still drop this control in the designer (which creates someCustomerNameUserControl1) and do this whenever you need to:
ICustomerName cName = someCustomerNameUserControl1;
Maybe I'm missing something, but I think it's that simple.

There's a way to accomplish what you want -- hiding the members you don't want to see -- but make it apply automatically, without requiring others' cooperation in terms of them using a custom interface. You can do it by reintroducing all the members you don't want to see, and tagging them with attributes.
This is what Windows Forms does when, for example, a base-class property doesn't mean anything for a particular descendant. For example, Control has a Text property, but a Text property is meaningless on, say, a TabControl. So TabControl overrides the Text property, and adds attributes to its override saying "By the way, don't show my Text property in the Property Grid or in Intellisense." The property still exists, but since you never see it, it doesn't get in your way.
If you add an [EditorBrowsable(EditorBrowsableState.Never)] attribute to a member (property or method), then Intellisense will no longer show that member in its code-completion lists. If I'm understanding your question correctly, this is the big thing you're trying to achieve: make it hard for application code to use the member by accident.
For properties, you probably also want to add [Browsable(false)] to hide the property from the Property Grid, and [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] to prevent the designer from writing the property's value to the .designer.cs file.
These will make it very difficult to accidentally use the method/property. They're still not a guarantee, though. If you do need a guarantee, then throw in an [Obsolete] attribute too, and build with "Treat warnings as errors" -- then you're taken care of.
If the base member is virtual, you probably want to override it, and have your override simply call base. Don't throw an exception, since the overridden member will probably be called by the base class during the normal course of events. On the other hand, if the base member isn't virtual, then you want to use "new" instead of "override", and you can decide whether your implementation should call base, or just throw an exception -- nobody should be using your reintroduced member anyway, so it shouldn't matter.
public class Widget : UserControl
{
// The Text property is virtual in the base Control class.
// Override and call base.
[EditorBrowsable(EditorBrowsableState.Never)]
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[Obsolete("The Text property does not apply to the Widget class.")]
public override string Text
{
get { return base.Text; }
set { base.Text = value; }
}
// The CanFocus property is non-virtual in the base Control class.
// Reintroduce with new, and throw if anyone dares to call it.
[EditorBrowsable(EditorBrowsableState.Never)]
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[Obsolete("The CanFocus property does not apply to the Widget class.")]
public new bool CanFocus
{
get { throw new NotSupportedException(); }
}
// The Hide method is non-virtual in the base Control class.
// Note that Browsable and DesignerSerializationVisibility are
// not needed for methods, only properties.
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("The Hide method does not apply to the Widget class.")]
public new void Hide()
{
throw new NotSupportedException();
}
}
Yes, this is a fair bit of work, but you only have to do it once... per member, per class... umm, yeah. But if those base-class members really don't apply to your class, and having them there will cause confusion, then it may be worth going to the effort.

'I want ICustomerName to be the only option for accessing the UserControl's variable. The idea is that a developer doesn't have to "just remember" to cast it.'
The problem you are having is that you have two completely divergent uses for your form and the controls it hosts. There is no trick built into Visual Studio or winforms which solves this neatly for you. It may be possible, but there is a much cleaner and object oriented way to separate the two methods of interacting with the controls.
If you want to hide the fact that these objects inherit from UserControl, and just want to treat them as IDoSomeThingYouShouldDealWith, you need to separate the logic that deals with the presentation concerns (designer + UI logic) from your business logic.
Your form class, should rightly deal with the controls as UserControls, docking, anchoring etc etc, nothing special here. You should put all the logic that needs to deal with ICustomerName.FirstName = etc into a completely separate class. This class doesn't care or know about fonts and layout, it just knows that there is another instance that can present a customer name; or a DateTime as a 'date of birth choosing' control properly etc.
This is a really lame example, but I have to go right now. You should be able to get the idea covered here in more detail:
public interface ICustomerName
{
void ShowName(string theName);
}
public partial class Form1 : Form, ICustomerName
{
public Form1()
{
InitializeComponent();
}
#region ICustomerName Members
public void ShowName(string theName)
{
//Gets all controls that show customer names and sets the Text propert
//totheName
}
#endregion
}
//developers program logic into this class
public class Form1Controller
{
public Form1Controller(ICustomerName theForm) //only sees ICustomerName methods
{
//Look, i can't even see the Form object from here
theForm.ShowName("Amazing Name");
}
}

After you add the UserControl using the designer, you can set GenerateMember to false in the Properties window to suppress generation of a member.
You could then use some other technique in the constructor to assign your cName reference, e.g.:
foreach(Control control in this.Controls)
{
cName = control as ICustomerName;
if (cName != null) break;
}
cName would then be the only reference to the UserControl.

You could write an extension method that would allow you to return any controls on the form that implement an interface.
public static class FormExtensions
{
public static IDictionary<string, T> GetControlsOf<T>(this Form form)
where T: class
{
var result = new Dictionary<string, T>();
foreach (var control in form.Controls)
{
if ((control as T) != null)
result.Add((control as T).Tag, control as T);
}
return result;
}
}
Then in your form you could call it whereever you want by:
this.GetControlsOf<ICustomerName>()["NameOfControlHere"];
In the event that it returns more than one user control you would need to handle that some how, perhaps by adding Tag property to the interface to uniquely keep track of each user control or something, like so
public partial class UserControl1 : UserControl, ICustomerName
{
public string Tag { get { return this.Name; } }
}
You can then drag and drop the user controls onto your form from the designer. Tag will always return the name of your control, which will allow you to directly access the control through the IDictionary's interface. You're developers could put whatever unique identifier they want in the name of the control, and it would carry through to the interface.
Also, it should be noted that this approach will ALSO allow you to use this on ALL forms in your solution.
The only other thing you would need to do is set your GenerateMember to false.

you could as well do as Bob said but assign all your member variables in the constructor, then you have it in one place.

It almost seems like you want to implement a mediator pattern. Instead of having to deal with each of the bazillion UserControls directly, you'd interact with them through the mediator. Each mediator would define the slim interface you want to see from each control. This would reduce the overall complexity by making your design more explicit and concise. For example, you wouldn't need the 20 properties and 50 methods available on one of your controls. Instead you'd deal with the mediator for that control which defines the 2 properties and 5 methods you really care about. Everything would still show up in the designer, but other parts of your app would not be interacting with those controls -- they'd interact with the mediators.
One of the big advantages to this approach is it greatly simplifies your maintenance. If you decide the MyCrappyUserControl needs to be rewritten because the implementation is bad, you just need to update the mediator class for that control. All the other classes that interact with the control do so through the mediator and would be unchanged.
Ultimately it comes down to discipline: you and your team need to be disciplined enough to use the mediators/interfaces/whatever instead of the directly hitting the controls. Institute an over the shoulder code review by a leader programmer if your team is on the low end of the discipline scale.

Assume that MyUserControl is defined like this:
class MyUserControl : UserControl, IMyInterface
{
// ...
}
Then in your form, you should have something like this:
public class MyForm : Form
{
IMyInterface cName;
public MyForm()
{
InitializeComponent();
cName = new MyUserControl();
Controls.Add((UserControl)cName);
}
}
This way, cName is the only way to access this instance of our usercontrol.

Related

C# User Control Dependency Injection [duplicate]

Call me crazy, but I'm the type of guy that likes constructors with parameters (if needed), as opposed to a constructor with no parameters followed by setting properties. My thought process: if the properties are required to actually construct the object, they should go in the constructor. I get two advantages:
I know that when an object is constructed (without error/exception), my object is good.
It helps avoid forgetting to set a certain property.
This mindset is starting to hurt me in regards to form/usercontrol development. Imagine this UserControl:
public partial class MyUserControl : UserControl
{
public MyUserControl(int parm1, string parm2)
{
// We'll do something with the parms, I promise
InitializeComponent();
}
}
At designtime, if I drop this UserControl on a form, I get an Exception:
Failed to create component 'MyUserControl' ...
System.MissingMethodException - No parameterless constructor defined for this object.
It seems like, to me, the only way around that was to add the default constructor (unless someone else knows a way).
public partial class MyUserControl : UserControl
{
public MyUserControl()
{
InitializeComponent();
}
public MyUserControl(int parm1, string parm2)
{
// We'll do something with the parms, I promise
InitializeComponent();
}
}
The whole point of not including the parameterless constructor was to avoid using it. And I can't even use the DesignMode property to do something like:
public partial class MyUserControl : UserControl
{
public MyUserControl()
{
if (this.DesignMode)
{
InitializeComponent();
return;
}
throw new Exception("Use constructor with parameters");
}
}
This doesn't work either:
if (LicenseManager.UsageMode == LicenseUsageMode.Designtime)
Fine, moving along ...
I have my parameterless constructor, I can drop it on the form, and the form's InitializeComponent will look like this:
private void InitializeComponent()
{
this.myControl1 = new MyControl();
// blah, blah
}
And trust me, because I did it (yes, ignoring the comments Visual Studio generated), I tried messing around and I passed parameters to InitializeComponent so that I could pass them to the constructor of MyControl.
Which leads me to this:
public MyForm()
{
InitializeComponent(); // Constructed once with no parameters
// Constructed a second time, what I really want
this.myControl1 = new MyControl(anInt, aString);
}
For me to use a UserControl with parameters to the constructor, I have to add a second constructor that I don't need? And instantiate the control twice?
I feel like I must be doing something wrong. Thoughts? Opinions? Assurance (hopefully)?
Design decisions made regarding the way Windows Forms works more or less preclude parameterized .ctors for windows forms components. You can use them, but when you do you're stepping outside the generally approved mechanisms. Rather, Windows Forms prefers initialization of values via properties. This is a valid design technique, if not widely used.
This has some benefits, though.
Ease of use for clients. Client code doesn't need to track down a bunch of data, it can immediately create something and just see it with sensible (if uninteresting) results.
Ease of use for the designer. Designer code is clearer and easier to parse in general.
Discourages unusual data dependencies within a single component. (Though even microsoft blew this one with the SplitContainer)
There's a lot of support in forms for working properly with the designer in this technique also. Things like DefaultValueAttribute, DesignerSerializationVisibilityAttribute, and BrowsableAttribute give you the opportunity to provide a rich client experience with minimal effort.
(This isn't the only compromise that was made for client experience in windows forms. Abstract base class components can get hairy too.)
I'd suggest sticking with a parameterless constructor and working within the windows forms design principles. If there are real preconditions that your UserControl must enforce, encapsulate them in another class and then assign an instance of that class to your control via a property. This will give a bit better separation of concern as well.
There are two competing paradigms for designing classes:
Use parameterless constructors and set a bunch of properties afterwards
Use parameterized constructors to set properties in the constructor
The Visual Studio Windows Forms Designer forces you to provide a parameterless constuctor on controls in order to work properly. Actually, it only requires a parameterless constructor in order to instantiate controls, but not to design them (the designer will actually parse the InitializeComponent method while designing a control). This means that you can use the designer to design a form or user control without a parameterless constructor, but you cannot design another control to use that control because the designer will fail to instantiate it.
If you don't intend to programmatically instantiate your controls (i.e. build your UI "by hand"), then don't worry about creating parameterized constructors, since they won't be used. Even if you are going to programmatically instantiate your controls, you may want to provide a parameterless constructor so they can still be used in the designer if need be.
Regardless of which paradigm you use, it is also generally a good idea to put lengthy initialization code in the OnLoad() method, especially since the DesignMode property will work at load time, but not work in the constructor.
I would recommend
public partial class MyUserControl : UserControl
{
private int _parm1;
private string _parm2;
private MyUserControl()
{
InitializeComponent();
}
public MyUserControl(int parm1, string parm2) : this()
{
_parm1 = parm1;
_parm2 = parm2;
}
}
As this way the base constructor is always called first and any references to components are valid.
You could then overload the public ctor if need be, ensuring the control is always instantiated with the correct values.
Either way, you ensure that the parameterless ctor is never called.
I haven't tested this so if it falls over I apologise!
This is unfortunately a design issue that will occur frequently, not just in the control space.
There are often situations where you need to have a parameterless constructor, even though a parameterless constructor is not ideal. For example, many value types, IMO, would be better off without parameterless constructors, but it's impossible to create one that works that way.
In these situations, you have to just design the control/component in the best manner possible. Using reasonable (and preferably the most common) default parameters can help dramatically, since you can at least (hopefully) initialize the component with a good value.
Also, try to design the component in a way that you can change these properties after the component is generated. With Windows Forms components, this is typically fine, since you can pretty much do anything until load time safely.
Again, I agree - this isn't ideal, but it's just something we have to live with and work around.
Well, in short, the designer is the kind of guy that likes parameter-less constructors. So, to the best of my knowledge, if you really want to use parameter based constructors you are probably stuck with working around it one way or the other.
Just do this:
public partial class MyUserControl : UserControl
{
public MyUserControl() : this(-1, string.Empty)
{
}
public MyUserControl(int parm1, string parm2)
{
// We'll do something with the parms, I promise
if (parm1 == -1) { ... }
InitializeComponent();
}
}
Then the 'real' constructor can act accordingly.
Provide a parameterless constructor for the designer and make it private - if you really must do it this way... :-)
EDIT: Well of course this won't work for UserControls. I obviously wasn't thinking clearly. The designer need to execute the code in InitializeComponent() and it's can't work if the constructor is private. Sorry about that. It does work for forms, however.
It's quite a while since the question was asked, but maybe my approach is helpful to somebody.
I personally also prefer to use parameterized Constructors to avoid forgetting to set a certain property.
So instead of using the actual Constructor I simply define a public void PostConstructor where all things are put you would normally put in the Constructor. So the Actual Constructor of the UserControl always contains only InitializeComponent().
This way you don't have to adjust your favourite programming paradigm to VisualStudios needs to run the Designer properly. For this programming schema to work it has to be followed from the very bottom.
In practice this PostConstructionalizm would look somewhat like this:
Let's start with a Control at the bottom of your UserControl call hierarchy.
public partial class ChildControl : UserControl
{
public ChildControl()
{
InitializeComponent();
}
public void PostConstructor(YourParameters[])
{
//setting parameters/fillingdata into form
}
}
So a UserControl containing the ChildControl would look something like that:
public partial class FatherControl : UserControl
{
public FatherControl()
{
InitializeComponent();
}
public void PostConstructor(YourParameters[])
{
ChildControl.PostConstructor(YourParameters[])
//setting parameters/fillingdata into form
}
}
And finally a Form calling one of the User Control simply puts the PostConstructor after InitializeComponent.
public partial class UI : Form
{
public UI(yourParameters[])
{
InitializeComponent();
FatherControl.PostConstructor(yourParameters[]);
}
}
I have a way to work around it.
Create a control A on the form with the parameterless constructor.
Create a control B with parameterized constructor in the form contstructor.
Copy position and size from A to B.
Make A invisible.
Add B to A's parent.
Hope this will help. I just encountered the same question and tried and tested this method.
Code for demonstrate:
public Form1()
{
InitializeComponent();
var holder = PositionHolderAlgorithmComboBox;
holder.Visible = false;
fixedKAlgorithmComboBox = new MiCluster.UI.Controls.AlgorithmComboBox(c => c.CanFixK);
fixedKAlgorithmComboBox.Name = "fixedKAlgorithmComboBox";
fixedKAlgorithmComboBox.Location = holder.Location;
fixedKAlgorithmComboBox.Size = new System.Drawing.Size(holder.Width, holder.Height);
holder.Parent.Controls.Add(fixedKAlgorithmComboBox);
}
holder is Control A, fixedKAlgorithmComboBox is Control B.
An even better and complete solution would be to use reflect to copy the properties one by one from A to B. For the time being, I am busy and I am not doing this. Maybe in the future I will come back with the code. But it is not that hard and I believe you can do it yourself.
I had a similar problem trying to pass an object created in the main Windows Form to a custom UserControl form. What worked for me was adding a property with a default value to the UserControl.Designer.cs and updating it after the InitializeComponent() call in the main form. Having a default value prevents WinForms designer from throwing an "Object reference not set to an instance of an object" error.
Example:
// MainForm.cs
public partial class MainForm : Form
public MainForm()
{
/* code for parsing configuration parameters which producs in <myObj> myConfig */
InitializeComponent();
myUserControl1.config = myConfig; // set the config property to myConfig object
}
//myUserControl.Designer.cs
partial class myUserControl
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
// define the public property to hold the config and give it a default value
private myObj _config = new myObj(param1, param2, ...);
public myObj config
{
get
{
return _config ;
}
set
{
_config = value;
}
}
#region Component Designer generated code
...
}
Hope this helps!

How To Get around multiple inheritance

I am trying to implement the following in C# so that I can force initialization of certain event delegates and variables in the parent classes, or I would use interface's instead. Obviously the below is not syntax correct.
the concrete class is Class1 & class 2.
the idea being here MyClass Is a button and it is an Image and it is something else.
Edit: " I understand that selectable and others are not objects but states. what I really want to do is to write the code that maintains the selectable state in the appropriate method because it will be the same for all of them. i.e. On click event( click location) check if i was I clicked based on my bounding box, update state to selected. I am in XNA, which is a c# polling environment, and I'm attempting to make the GUI as event driven as possible, if that makes any sense? "
public abstract class Class1
{
private int NumberNeededForMethod;
private void methodThatOccursWhenEventHappens(int NumberNeededForMethod)
{
// stuff using NumberNeededForMethod;
}
private Class1(int NumberNeededForMethod)
{
MethodDelegate += methodThatOccursWhenEventHappens(int
NumberNeededForMethod)
;
}
}
public abstract class Class2
{
private int NumberNeededForMethod2;
private void methodThatOccursWhenEventHappens2(int NumberNeededForMethod2)
{
// stuff using NumberNeededForMethod2;
}
Class2(int NumberNeededForMethod2)
{
MethodDelegate += methodThatOccursWhenEventHappens(int NumberNeededForMethod2);
}
}
public class ClassThatIsBothClass1andClass2: Class1, Class2
{
ClassThatIsBothClass1andClass2( int NumberNeededForMethod1, int NumberNeededForMethod2) : Class1(NumberNeededForMethod1),Class2(NumberNeededForMethod2)
{
}
}
You can use composition to create a class which wraps class1 and class2 and is the thing that responds to the event raised by your button.
First, of course, C# does not support multiple inheritance, so whatever polymorphism you implement will have to be accomplished using interfaces and composition.
Referring to this comment: Draggable, Selectable and Ownable are attributes of an object.
Image and Button, on the other hand, are objects.
A Button cannot be an Ownable.
But a Button can be Ownable, Draggable or Selectable. What I wonder is whether those attributes aren't just properties on a single IAshtonControl interface?
A Button can conceivably also be an Image. That makes perfect sense.
Because C# lacks multiple inheritance, you simply cannot create an AshtonButton class that derives from both Button and Image base classes.
One thing you can do is create an AshtonButton class that implements the IAshtonControl interface, and the implementation for that interface can delegate to a private instance of a worker class that does whatever work is common to all IAshtonControl instances.
Or you could have separate IOwnable, IDraggable and ISelectable interfaces if that is what is required.
Either way, it becomes possible to truthfully make the statement that AshtonButton is an IAshtonControl, is ownable, is draggable, is selectable. Those things might have different meanings (different behavior/visual effects) for different controls, or they might not, but you would hide those implementation details behind the interface(s) so that you could programmatically treat each object the same way regardless of its implementation.
It is important to separate the object from its attributes, because that affects the way you think about the problem. Draggable is not a thing, it is a characteristic of a thing.
But if your goal is to have a Button that is also an Image, some type of composition or delegation is the way to accomplish that. If you have a IAshtonImage interface, then you would implement that on both the AshtonImage class, and on the AshtonImageButton class. Then you have an internal instance (composition) of the AshtonImage class, within the AshtonImageButton class, and delegate calls to the IAshtonImage members through to the private (composed) AshtonImage instance, and so on.

How to override a dependency properties in a generic class?

So I have a class; lets use the ScrollViewer class as an example. It has a dependency property called Content which accepts anything of type System.Object, great!
Let's say I derive a class from ScrollViewer, lets call it ZoomScrollViewer, it adds some basic zooming and panning using the mouse with a keyboard press. It also adds a dependency property of it's own, AutoscaleContent.
Now, I want to be able to put a ZoomScrollViewer into a UI window, but I only want it to accept a Canvas as it's content. Naturally, I go about creating a ZoomScrollViewer<T> class.
However, how can I change the Content property so that only accepts elements of type <T>? Can I override the dependency property? I got a little confused and tried:
public new T Content
{
get { return (T)base.Content; }
set { base.Content = value; }
}
But of course this makes it no longer a dependency property, so all the XAML code fails when I set up the bindings.
Edit: It should also be noted that I've taken a look at using:
ZoomScrollViewer.ContentProperty.OverrideMetadata(typeof(ZoomScrollControl2<T>), new PropertyMetadata(...?));
To see if I could do anything using that, but it seems you can only override the default value, unless I'm missing something?
Update: I've now tried using the following:
public class ZoomScrollControl2<T> : ZoomScrollViewer where T : FrameworkElement
{
static ZoomScrollControl2()
{
ContentProperty.OverrideMetadata(typeof(ZoomScrollControl2<T>), new FrameworkPropertyMetadata(typeof(ZoomScrollControl2<T>)));
}
}
public class CanvasZoomControl : ZoomScrollControl2<Canvas>
{
}
Which I thought would work, but it still seems to accept a Content of any type.
Update: In short I'm not sure if what I want to do is even possible, so I've marked the discussion as the answer, even though it isn't an answer per-se.
I suggest to try that approach as it suggested by this MSDN article.
It should override the referal type, so you can refer to it using derived type.
Dependency Property visibility is not made esplicit in .NET Framework for derived types, as searching right property among the types tree has a cost in terms of performance, and considering that we use DP on UI binding, it can lead to non desirable performance issues.

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.
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();)
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.
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.
You're out of luck :-(
You could write your own class that wraps the WorkItemType and delegate down to it (a proxy) expect for the ToString:
class MyWorkItemType
{
private WorItemType _outer;
public MyWorkItemType(WorkItemType outer)
{
_outer=outer;
}
public void DoAction()
{
_outer.DoAction();
}
// etc
public override string ToString()
{
return "my value"
}
}
I don't have any C# knowledge, but can't you wrap your extended class inside another class? Proxy all method calls to the extended class, except toString(), Also very hackish, but I thought I'ld bring it up anyway.
Doing some sorta magic with reflection is probably your only hope. I know you can instantiate private constructors with it, so maybe you can override a sealed class... Note, this should be your last resort if there is seriously no other way. Using reflection is a very hackish/improper way of doing it.
In addition to the other WPF-specific answer you could use an IValueConverter in the binding to format / display the WorkItemType however you want. This has an advantage of being reusable (if you want to display the object in some other control, for instance.)
There are many examples of using converters here. This other question should be pretty similar to the ComboBox usage mentioned here. The answers note that you can either make the converter work on the entire collection of objects, or work on one item at a time. The latter might be the more reusable approach.

Hiding unwanted properties in custom controls

Is this the way to hide properties in derived controls?
public class NewButton : Button
...
[Browsable ( false )]
public new ContentAlignment TextAlign { get; set; }
Also this hides the property in the Properties window in the designer but how can I also hide the property in code?
From code, the closest you can do it to hide it, and perhaps make it a pain to call directly - note that even when hidden it is callable, and none of this will work past a cast:
// about the closest you can do, but not really an answer
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("just cast me to avoid all this hiding...", true)]
public new ContentAlignment TextAlign { get; set; }
Personally, I wouldn't bother. It isn't robust (just cast).
You can use the [EditorBrowsable] attribute, as documented here.
[EditorBrowsable(EditorBrowsableState.Never)]
public bool HideMeInIntellisense
{
// ...
From the documentation:
...the IntelliSense engine in Visual Studio uses this attribute to determine whether to show a property or method.
However, users can override this in VS settings. ReSharper also has a setting that controls whether this attribute is honoured in its IntelliSense.
Out of curiousity, why do you want to hide something from users? Just because a member is hidden in the way described above doesn't mean you couldn't use it in code and compile it successfully. It just inhibits the discoverability of the member.
No, you can remove them from the designer (as shown) but you cannot really hide them form code as that would violate the substitution principle. It has been asked & answered many times here, see for example this SO question.
Maybe what you want to do is derive from ContainerControl or UserControl, add a Button to that control and just expose those parts of the Button interface you want to keep.
Why don't you make it private? It guarantees that ancestors will not see it.
Edit:
In this case you have to inherit a new class from the base and use your new class, which now hides ths property.
public class MyTextBox: TextBox
{
...
private new ContentAlignment TextAlign
{
get { return base.ContentAlignment; }
set { base.ContentAlignment = value; }
}
}

Categories

Resources