convert code from win form to devexpress - c#

This code use with code of win form.So I want to use it with DevExpress and the problem is I don't know which tool in DevExpress that I can use instead of this code.I have a class below: Thanks
using System.Drawing;
using System;
namespace Extender
{
public class MenuItem : System.Windows.Forms.ToolStripMenuItem
{
private string _Command;
public string Command
{
get
{
return _Command;
}
set
{
_Command = value;
}
}
private object _Argument;
public object Argument
{
get
{
return _Argument;
}
set
{
_Argument = value;
}
}
private Int16 _ModuleID;
public Int16 ModuleID
{
get
{
return _ModuleID;
}
set
{
_ModuleID = value;
}
}
public MenuItem()
{
}
public MenuItem(string text)
{
this.Text = text;
}
public MenuItem(string text, EventHandler onclick) :
this(text)
{
this.Click += onclick;
}
}
}
And the code below is the method that I use to create menu from database using entity framework with winform
private void LoadMenus(ToolStripItemCollection Menu,string ParentName)
{
using (var ctx = new CambbusEntities())
{
foreach (var obj in ctx.view_ObjectDetails.Where(a => a.ObjectType == "MENU" && a.ParentName==ParentName &&a.LanguageID == Cambbus.Properties.Settings.Default.LanguageID ).OrderBy(a=>a.SortOrder))
{
string mText = obj.ObjectText;
string nName = obj.ObjectName;
if (mText == "-")
continue;
Extender.MenuItem m = new Extender.MenuItem(mText);
m.Alignment = ToolStripItemAlignment.Left;
//m.Text = obj.ObjectText;
//m.Name = obj.ParentName;
m.ModuleID = (Int16)obj.ModuleID;
m.Command = obj.Command;
m.Argument = obj.Argument;
m.Image = App.GetImageByEntity((obj.ImageTag)+"");
if (m.Command!=""){
m.Click += DynamicMenuClick;
}
bool Is4Perm = obj.ModuleID > 0;
if(Is4Perm){
m.Enabled = CurrentUser.CanViewModule((Int16)obj.ModuleID);
}
Int16 shortcutNum = ((Int16)(obj.ShortcutNum));
if (shortcutNum != 0)
{
m.ShortcutKeys = ((System.Windows.Forms.Keys)(Keys.Control)) | ((System.Windows.Forms.Keys)(shortcutNum));
}
Menu.Add(m);
LoadMenus(m.DropDownItems,nName);
}
}
}
The problem is I don't know the properties of DevExpress that can use instead winform. So can I use DevExpress instead of winform?
this is my image of winform
and I want to change to DevExpress same as in picture DevExpress Menu by using my class and method.thanks

DevExpress bars have several types of menu item. Their list is available at The List of Bar Items and Links. Since you need to handle a click on an item, I think you need BarButtonItem. You can set its caption by using the BarButtonItem.Caption property. For a click, handle the BarItem.ItemClick event.
Edited
With DevExpress, you can replace the orange tool bar with a Bar. For this, simply place BarManager on your form. It creates some default bars. Program, Sales, Help, etc. commands can be replaced with BarButtonItems as I described above. Listings and its sub items can be done by using BarSubItem. I see that you have the Windows item. If your application is MDI, I suggest you use BarMdiChildrenListItem. It will automatically generate items for all MDI child forms.
If you need to generate items in code, refer to the BarManager Class help topic that provides some code for this.

Related

Generate custom C# code in Form.cs while dropping user control in Form1.cs at design time

I have a user control that I can drag and drop in the Form1.cs[Design] mode. The designer will auto-generate code for this user control in the Form1.Designer.cs
What I would like to get aswell is: at the moment I am adding the user control to the form by dragging I wont to have code generated in my Form.cs that is pointing to the properties and controls on that user control.
Example of user control:
public partial class UserControl1 : UserControl
{
public UserControl1()
{
InitializeComponent();
}
public string TextInTextBox
{
get { return textBox1.Text; }
set { textBox1.Text = value; }
}
}
So now when I drag it on the form in the Form1.cs[Design]. I won't part of code like this to be generated in my Form1.cs:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
AddText();
}
// this code below to be auto-generated
private void AddText()
{
userControl11.TextInTextBox = "";
}
}
I think I should be looking for something like inheritance or interface but I would like this to happen for each instance of that user control.
If someone could point me direction what to look for it would be great. Thanks.
Usually you don't need to generate code manually when you want to assign a property when dropping a control from toolbox, for example you can easily do this:
public MyUserControl()
{
InitializeComponent();
MyTextProperty = "Something";
}
And it will be serialized automatically.
But there are more options for more advanced requirements.if you know the options that you have, you may choose based on your requirement. Here is some options:
Assign some value in constructor or to the property
Assign value to properties using ToolboxItem, it will overwrite the value which you assign in constructor.
Generate some code for Load event of form and initialize property there. It's useful for complex code generations, for example when you drop a data source it will generate some code to load data and add to load event of form.
Assuming you have assigned Something to MyTextProperty in constructor, then when you drop the control in form, here is what will be generated in designer.cs:
this.myUserControl1.MyTextProperty = "Something";
If you use the ToolboxItem solution to assign Something else to the property, the result in designer.cs file will be:
this.myUserControl1.MyTextProperty = "Something else";
And if you decide to use third option and generate event handler code, the result in designer.cs file will be:
this.Load += new System.EventHandler(this.Form1_Load);
and the result in cs file will be:
private void Form1_Load(object sender, EventArgs e)
{
myUserControl1.MyTextProperty = "Even something else!";
}
Example
Here is a full code of MyUserControl, MyUserControlToolboxItem and MyUserControlDesigner. You can comment Designer and/or ToolboxItem attributes and close all designers and clean and rebuild the solution and drop an instance of the control on the form to see how it works.
using System.CodeDom;
using System.Collections;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Drawing.Design;
using System.Linq;
using System.Windows.Forms;
using System.Windows.Forms.Design;
[Designer(typeof(MyUserControlDesigner))]
[ToolboxItem(typeof(MyUserControlToolBoxItem))]
public partial class MyUserControl : UserControl
{
public MyUserControl()
{
InitializeComponent();
}
public string MyTextProperty { get; set; } = "Something";
}
public class MyUserControlToolBoxItem : ToolboxItem
{
protected override IComponent[] CreateComponentsCore(IDesignerHost host)
{
IComponent[] componentsCore = base.CreateComponentsCore(host);
if (componentsCore != null && componentsCore.Length > 0
&& componentsCore[0] is MyUserControl)
(componentsCore[0] as MyUserControl)
.MyTextProperty = "Something else"; ;
return componentsCore;
}
}
public class MyUserControlDesigner : ControlDesigner
{
public override void InitializeNewComponent(IDictionary defaultValues)
{
base.InitializeNewComponent(defaultValues);
var component = Control;
var eventBindingService = (IEventBindingService)this.GetService(
typeof(IEventBindingService));
var componentChangeService = (IComponentChangeService)this.GetService(
typeof(IComponentChangeService));
var designerHostService = (IDesignerHost)GetService(typeof(IDesignerHost));
var rootComponent = designerHostService.RootComponent;
var uiService = (IUIService)GetService(typeof(IUIService));
var designerTransaction = (DesignerTransaction)null;
try
{
designerTransaction = designerHostService.CreateTransaction();
var e = TypeDescriptor.GetEvents(rootComponent)["Load"];
if (e != null)
{
var methodName = "";
var eventProperty = eventBindingService.GetEventProperty(e);
if (eventProperty.GetValue(rootComponent) == null)
{
methodName = eventBindingService
.CreateUniqueMethodName(rootComponent, e);
eventProperty.SetValue(rootComponent, methodName);
}
else
methodName = (string)eventProperty.GetValue(rootComponent);
var code = this.GetService(typeof(CodeTypeDeclaration))
as CodeTypeDeclaration;
CodeMemberMethod method = null;
var member = code.Members.Cast<CodeTypeMember>()
.Where(x => x.Name == methodName).FirstOrDefault();
if (member != null)
{
method = (CodeMemberMethod)member;
method.Statements.Add(
new CodeSnippetStatement($"{Control.Name}" +
$".MyTextProperty = \"Even something else!\";"));
}
componentChangeService.OnComponentChanged(rootComponent,
eventProperty, null, null);
eventBindingService.ShowCode(rootComponent, e);
}
designerTransaction.Commit();
}
catch (System.Exception ex)
{
if (designerTransaction != null)
designerTransaction.Cancel();
uiService.ShowError(ex);
}
}
}

Setting default size/text of custom control in c#

I am creating a custom control in my C# application in order to add a new property (MyProperty below). It is inheriting from Label. One thing I would like it to do, is display at a particular size when I drag it on to my form (200x132). I'd also like it to display no text. However, no matter how I try to do this, it doesn't seem to work. I am able to set BackColor and BorderStyle with no problem, however. I'm fairly new to C#, so maybe I'm missing something obvious.
Here is my code:
using System.Drawing;
using System.Windows.Forms;
namespace MyProgram
{
public enum MyEnum
{
Value1, Value2, Value3
}
public partial class MyControl : Label
{
public MyControl()
{
BackColor = Color.LightCoral;
BorderStyle = BorderStyle.FixedSingle;
AutoSize = false;
Size = new Size(200, 132);
Text = "";
InitializeComponent();
}
protected override void OnPaint(PaintEventArgs pe)
{
base.OnPaint(pe);
}
private MyEnum myProperty;
public MyEnum MyProperty
{
get { return myProperty; }
set { myPropery = value; }
}
}
}
The answer provided via Dispersia's link has a bug, in my opinion. The text reset should happen once and then whatever a user does after that shouldn't matter. In Dispersia's link you can't actually set the text back to the control name because it will keep blanking it out.
The answer provided by cramopy doesn't technically answer your question, it is a way to do it by using the defaults on a UserControl though. You'll also need to bind the Text property of the UserControl to the label's.
The following should work while inheriting from a Label and will only reset the Text property once.
public partial class MyControl : Label
{
#region fields
private IComponentChangeService _changeService;
private bool canResetText = false;
#endregion
#region properties
protected override Size DefaultSize
{
get { return new Size(200, 132); }
}
[Browsable(false)]
public override bool AutoSize
{
get { return false; }
set { base.AutoSize = false; }
}
public override ISite Site
{
get { return base.Site; }
set
{
base.Site = value;
if (!base.DesignMode)
return;
this._changeService = (IComponentChangeService)base.GetService(typeof(IComponentChangeService));
if (this._changeService != null)
this._changeService.ComponentChanged += new ComponentChangedEventHandler(this.OnComponentChanged);
}
}
#endregion
#region constructors
public MyControl()
{
base.BackColor = Color.LightCoral;
base.BorderStyle = BorderStyle.FixedSingle;
}
#endregion
#region methods
protected override void InitLayout()
{
base.InitLayout();
this.canResetText = true;
}
private void OnComponentChanged(object sender, ComponentChangedEventArgs ce)
{
if (ce.Component != null &&
ce.Component == this &&
ce.Member.Name == "Text" &&
base.DesignMode &&
this.canResetText)
{
((MyControl)ce.Component).Text = string.Empty;
this.canResetText = false;
if (this._changeService != null)
this._changeService.ComponentChanged -= new ComponentChangedEventHandler(this.OnComponentChanged);
}
}
#endregion
}
#Dispersia reply only answers the myControl1 thing. (deleted meanwhile)
Here comes a full guide for solving your problem:
Add a new UserControl named MyLabel
Change the following within Designer Mode:
BorderStyle:= FixedSingle
Size:= 200; 132
Now Drag&Drop a new Label onto the control
Edit those Label values (also within Designer Mode):
AutoSize:= false
BackColor:= LightCoral
Dock:= Fill
Text:= clear/empty this box!! (don't write this inside the box, you really have to clear it!)
TextAlign:= MiddleCenter
Just recompile your project && add a MyLabel control from the Toolbar.
Now it show up as you wanted!!

How do I pass values to user control? [duplicate]

This question already has answers here:
How to pass values to a user control in winforms c#
(2 answers)
Closed 8 years ago.
I have a windows form and I want to pass a value to a user control. I programmatically create the user control in the winform and set a value, but it doesn't get set. Here is the code where I create the user control:
namespace AddPanel
{
public partial class Form1 : Form
{
public Form1()
{
int a = db.CamTable1s.Count();
InitializeComponent();
DisplayImage(a);
}
private void DisplayImage(int rowNum)
{
test nt = new test();
nt.Location = new System.Drawing.Point(33, h);
nt.Name = "test1";
nt.usrID = "username";
nt.Size = new System.Drawing.Size(408, 266);
this.Controls.Add(nt);
}
}
}
I set a variable I made in test user control called nt.Name, then I just want to display it in a text box on the user control. Here is the code for the user control:
namespace AddPanel
{
public partial class test : UserControl
{
public string usrID { get; set; }
public test()
{
InitializeComponent();
//textBox1.Text = usrID;
}
public test(string Id)
{
InitializeComponent();
usrID = Id;
UCtextBox.Text = usrID;
}
}
}
Obviously, I don't know why this isn't working. Could someone help me out?
Even in WPF, where you have bindings, the UI will not automatically pick up a change to a property (without raising PropertyChanged). It definitely won't in the hard-coded land of WinForms.
So you have two problems:
You invoked the default constructor in your call, so no code ever sets the Text property of the textbox
Even if you had set the text, the subsequent change to the property would not propagate to the UI.
The simplest solution would be to just run the UI update in the setter:
private string usrID;
public string UserID //Correct style!
{
get { return usrID; }
set
{
usrID = value;
RCtextBox.Text = usrID;
}
}
You could also call a method from the setter, listen on INotifyPropertyChanged and a number of other things.
Another way would be to expose a method instead of a property:
public string UpdateUserID(string newId)
{
usrID = newId;
RCtextBox.Text = usrID;
}
You should put value passed into usrId property to the textbox.
public partial class test : UserControl
{
public string usrID
{
get{return _usrId;}
set
{
_usrId = value;
UCtextBox.Text = value;
}
}

WPF Binding and Custom ListView and ListViewItems

I need a WPF control that functions similar to the 'Resolve Conflicts' window in TFS, and other similar source control systems.
I have the following classes
public class Conflict:INotifyPropertyChanged
{
private string _name;
private List<Resolution> _resolutions;
private bool _focused;
private bool _hasResolutions;
public string Name
{
get { return _name; }
set
{
_name = value;
OnPropertyChanged("Name");
}
}
public List<Resolution> Resolutions
{
get { return _resolutions; }
set
{
_resolutions = value;
OnPropertyChanged("Resolutions");
}
}
public bool Focused
{
get { return _focused; }
set {
_focused = value;
OnPropertyChanged("Focused");
}
}
public bool HasResolutions
{
get { return _resolutions.Any(); }
set
{
_hasResolutions = value;
OnPropertyChanged("HasResolutions");
}
}
}
public class Resolution
{
public string Name { get; set; }
public void Resolve()
{
//Logic goes here
}
}
This almost identical to the functionality of the Team Foundation Server (TFS) 'Resolve Conflict' window shown below:
For each row in the image above, it is the same as my Conflcit object, and for each of the buttons, would be one of the Resolution objects on the Conflict object.
My plan was to bind my List to a ListView, and then write a custom template or whatever to hide/show the buttons below it based on if it was selected or not.
To try to simplify what I need to accomplish, I have a List and I want to bind it to a control, and it look as close to the image above as possible.
How would I accomplish this and XAML and the code behind?
Here is an example of how you can dynamically create a data template, and add buttons based on your Conflict objects:
public DataTemplate BuildDataTemplate(Conflict conflict)
{
DataTemplate template = new DataTemplate();
// Set a stackpanel to hold all the resolution buttons
FrameworkElementFactory factory = new FrameworkElementFactory(typeof(StackPanel));
template.VisualTree = factory;
// Iterate through the resolution
foreach (var resolution in conflict.Resolutions)
{
// Create a button
FrameworkElementFactory childFactory = new FrameworkElementFactory(typeof(Button));
// Bind it's content to the Name property of the resolution
childFactory.SetBinding(Button.ContentProperty, new Binding("Name"));
// Bind it's resolve method with the button's click event
childFactory.AddHandler(Button.ClickEvent, new Action(() => resolution.Resolve());
// Append button to stackpanel
factory.AppendChild(childFactory);
}
return template;
}
You can do this in many different ways and this is just one of them.
I haven't test it, but this should be enough to get you started :)
Good luck

C#: data binding a single, custom class to form controls (checkbox?)

I'm writing a desktop application in Visual Studio 2008 / C#
I finished (mostly) writing an engine which generates a working schedule for the week for a small company; a form of a course-scheduling problem
Right now I'm designing a form in which the user can determine the initial parameters, or criteria, for the engine to adhere to (as some settings are optional)
I've got a class named EngineParameters, which holds all of those settings.
For the purpose of databinding, I created a bndEngineParameters class, which encapsulates all the relevant fields with getters and setters
public class bndEngineParameters
{
private engineParameters _parameters;
public bndEngineParameters(engineParameters ep)
{
this._parameters = ep;
}
public bool avoidGrouping
{
get { return _parameters.avoidGrouping; }
set { _parameters.avoidGrouping = value; }
}
public bool avoidWeekends
{
get { return _parameters.avoidWeekends; }
set { _parameters.avoidWeekends = value; }
}
public bool keyFlow
{
get { return _parameters.keyFlow; }
set { _parameters.keyFlow = value; }
}
public bool keyFlowAssistants
{
get { return _parameters.keyFlowAssistants; }
set { _parameters.keyFlowAssistants = value; }
}
}
It's not complete - there will be int values (maximum number of hours one can work etc.); I want those bool values to be bound to checkboxes on my form
And it's at that trivial task where I surprisingly ran into problems
Using "Add New DataSource" wizard, I created a binding source
private System.Windows.Forms.BindingSource bndEngineParametersBindingSource;
I then bound the Checked property of my Checkbox to the respective property of my binding source:
I implemented a local variable boundParameters so that I get an access to the parameters set by the user
public partial class formGenerateRota : Form
{
public bndEngineParameters boundParameters;
// (...)
public formGenerateRota()
{
InitializeComponent();
}
private void formGenerateRota_Load(object sender, EventArgs e)
{
boundParameters = new bndEngineParameters(new engineParameters());
bndEngineParametersBindingSource.Add(boundParameters);
}
// (...)
}
And what? Nothing happens. There is an bndEngineParameters object under bndEngineParametersBindingSource.Current (in run-time of course), but the avoidWeekends value never changes (when I check the checkbox on and off), and the bndEngineParametersBindingSource_CurrentItemChanged event is never fired
What's wrong?
SORRY! it does change, but only after the checkbox loses focus (after validation).
I'm stupid sometimes
If I'm doing something wrong anyway (I'm not any good with data binding), I'd very much appreciate if you point it out of course!
Two common issues:
set the DataSourceUpdateMode to OnPropertyChanged
(optional) to receive changes from the object, implement the {name}Changed event pattern or INotifyPropertyChanged
To be honest though, I'm sure most of that isn't necessary; you should just be able to say:
myCheckbox.Bindings.Add("Checked", myEngineParameters, "avoidWeekends",
false, DataSourceUpdateMode.OnPropertyChanged);
Full example:
using System;
using System.Diagnostics;
using System.Windows.Forms;
class EngineParameters {
private bool avoidWeekends;
public bool AvoidWeekends {
get { return avoidWeekends; }
set {
avoidWeekends = value;
Debug.WriteLine("AvoidWeekends => " + value);
}
}
}
static class Program {
[STAThread]
static void Main() {
Application.EnableVisualStyles();
using(Form form = new Form())
using (CheckBox myCheckbox = new CheckBox()) {
EngineParameters myEngineParameters = new EngineParameters();
myEngineParameters.AvoidWeekends = true;
form.Controls.Add(myCheckbox);
myCheckbox.DataBindings.Add("Checked", myEngineParameters, "AvoidWeekends",
false, DataSourceUpdateMode.OnPropertyChanged);
Application.Run(form);
}
}
}
Instead of this:
bndEngineParametersBindingSource.Add(boundParameters);
do this:
bndEngineParametersBindingSource.DataSource = boundParameters;

Categories