How can I show my enum in XAML? - c#

This is my custom textBox:
public class TextBoxInputNumbers : TextBox
{
Regex regex;
public enum DatatypesInput
{
Integer, Decimals
}
public TextBoxInputNumbers()
{
DatatypeInput = DatatypesInput.Integer;
}
public DatatypesInput DatatypeInput
{
set
{
switch (value)
{
case DatatypesInput.Integer:
regex = new Regex("[^0-9.-]+");
break;
case DatatypesInput.Decimals:
regex = new Regex("[^0-9-]+");
break;
}
}
}
protected override void OnPreviewTextInput(System.Windows.Input.TextCompositionEventArgs e)
{
e.Handled = regex.IsMatch(e.Text);
}
}
And I'd like to show the property DatatypeInput in XAML, but they cannot recognize any element of my enum.

You can convert the enun name to a string using the Enum.GetName() method:
get
{
return Enum.GetName(typeof(DatatypesInput), value);
}
and then bind to that value in your XAML.
Is that what you are looking for? Use Enum.GetNames() is you need the list of all valid names.

Related

Code snippet: create an "alias" for something else

I was looking for a similar way to create an alias for something else like its possible in C using preprocessor (this question is a bit similar, couldn't find anything useful there).
This is the problem: I've got a method that receives an array, but each position of the array has a specific meaning, like they where different parameters with specific names. What I want to do is to make my code easier to read (and write) by using those specific names, but, on the other hand, I don't want to create another method call (like in example 1) nor assign the array positions to new variables (example 2), because the performance is critical.
Example 1:
void OriginalMethodSignature(Type[] values)
{
SimplifiedMethod(values[0], values[1], ... values[n]);
}
void SimplifiedMethod(Type specificName1, Type specificName2, ... Type specificNameN)
{
// simple implementation using specific names instead of values[n]
}
Example 2:
void OriginalMethodSignature(Type[] values)
{
Type specificName1 = values[0];
Type specificName2 = values[1];
...
Type specificNameN = values[n];
// simple implementation using specific names instead of values[n]
}
I cannot change the method signature because its used in a dellegate, the Type is fixed.
The next example is a bit better, but still not optimum:
void OriginalMethodSignature(Type[] values)
{
// implementation using values[specificName1] ... values [specificNameN]
}
const int specificName1 = 0;
const int specificName2 = 1;
...
const int specificNameN = n-1;
Is there any way to create an snippet for this purpose? If yes, how would it be?
There isn't any built in way to do what you wan't, because you shouldn't really be doing it at all. You should be using an object with properties instead of an array.
Anyway, you can make an object that encapsulates the array, so that the properties use the array as storage:
public class NamedObject {
private Type[] _values;
public NamedObject(Type[] values) {
_values = values;
}
public SpecificName1 { get { return _values[0]; } set { _values[0] = value; } }
public SpecificName2 { get { return _values[1]; } set { _values[1] = value; } }
public SpecificName3 { get { return _values[2]; } set { _values[2] = value; } }
public SpecificName4 { get { return _values[3]; } set { _values[3] = value; } }
public SpecificName5 { get { return _values[4]; } set { _values[4] = value; } }
public SpecificName6 { get { return _values[5]; } set { _values[5] = value; } }
}
Now you can use the object to access the array:
void OriginalMethodSignature(Type[] values) {
NamedObject obj = new NamedObject(values);
// get a value
Type x = obj.SpecificName4;
// set a value
obj.SpecificName2 = x;
}
Create a dedicated class or struct, and parse the array into it.
public class MyClassOfStuff
{
Type SpecificName1 {get;set;}
Type SpecificName2 {get;set;}
public static MyClassOfStuff Parse(Type[] value)
{
Type specificName1 = values[0];
Type specificName2 = values[1];
...
Type specificNameN = values[n];
}
}
void OriginalMethodSignature(Type[] values)
{
var mystuff = MyClassOfStuff.Parse(values);
}

how to make read only property available in my usercontrol

i make user control from 3 text boxes but i don not how to declare read only property to it i tried many things but it do not work here is my code to make the control
i want to make it read only when needed like if i add checkbox i want if checkbox.check=true make my control readonly
public partial class dateIN : UserControl
{
Dates datess = new Dates();
public dateIN()
{
InitializeComponent();
}
private void dateIN_Leave(object sender, EventArgs e)
{
if (txtDay.Text != "" || txtMonth.Text != "" || txtYear.Text != "")
{
if (!datess.IsHijri(txtDay.Text.Trim() + "/" + txtMonth.Text.Trim() + "/" + txtYear.Text.Trim()))
{
txtDay.Focus();
}
}
}
public string Day
{
set { txtDay.Text = value; }
get { return txtDay.Text; }
}
public string Month
{
set { txtMonth.Text = value; }
get { return txtMonth.Text; }
}
public string Year
{
set { txtYear.Text = value; }
get { return txtYear.Text; }
}
need to know how to make read only property available here plz
just remove the set { } part of the property
Example:
public string Day
{
get { return txtDay.Text; }
}
I dont know the correlation of where your "txtDay", "txtMonth", "txtYear" come from, but you could do something like
public partial class dateIN : UserControl
{
...
...
private bool AllowEditing()
{ return SomeCondition when SHOULD be allowed...; }
public string Day
{
// only allow the set to apply the change if the "AllowEditing" condition
// is true, otherwise, ignore the attempt to assign.
set { if( AllowEditing() )
txtDay.Text = value; }
get { return txtDay.Text; }
}
// same concept for month and year too
}
so may you add some flag to your set when it is true then you set a value.
also you can work with textbox property called ReadOnly.

Use Class property value for a switch statement

am using generated protobuf code (see http://code.google.com/p/protobuf/)
I have a generated class looks like this :
public class Fruits{
private int _ID_BANANA = (int)1;
private int _ID_APPLE = (int)2;
public int ID_BANANA
{
get { return _ID_BANANA; }
set { _ID_BANANA = value; }
}
public int ID_APPLE
{
get { return _ID_APPLE; }
set { _ID_APPLE = value; }
}
}
Then they are constant values but I can't use then as such in my code.
For example I want to do a mapper like this :
public static Color GetColor(int idFruit) {
switch (idFruit)
{
case new Fruits().ID_BANANA:
return Color.Yellow;
case new Fruits().ID_APPLE:
return Color.Green;
default:
return Color.White;
}
}
I have the error : a constant value is expected.
I thougth about creating an enum, but seems to be the wrong way, tryed something like :
public const int AppleId = new Fruits().ID_APPLE;
Not working either...
Someone have an idea?
Why not to use if else if statements here?
var fruits = new Fruits();
if (idFruit == fruits._ID_BANANA)
return Color.Yellow;
else if (idFruit == fruits._ID_APPLE)
return Color.Green;
else
return Color.White;
Or dictionary:
this.fruitsColorMap = new Dictionary<int, Color>
{
{ fruits._ID_BANANA, Color },
{ fruits._ID_APPLE, Green }
};
And then:
public static Color GetColor(int idFruit) {
if (this.fruitsColorMap.ContainsKey(idFruit) {
return this.fruitsColorMap[idFruit];
}
return Color.White;
}
The case values in a switch statement have to be constants - that's part of the switch statement's definition:
switch (expression)
{
case constant-expression:
statement
jump-statement
[default:
statement
jump-statement]
}
as per the switch (C#) documentation from Microsoft.
you will notice the constant-expression bit. That means that it can be determined at compile time. So calls to functions (and a reference to a property property is really a function call in disguise) are not allowed here.

Convert String in to Enum Without knowing it's type in C#

I am facing a problem. I have set of some enum in my app. Like
public enum EnmSection
{
Section1,
Section2,
Section3
}
public enum Section1
{
TestA,
TestB
}
public enum Section2
{
Test1,
Test2
}
EnmSection is main enum which contains the other enum(as string) which are declared below it. Now i have to fill the values of EnmSection in a drop-down.I have done it.
Like this...
drpSectionType.DataSource = Enum.GetNames(typeof(EnmSection));
drpSectionType.DataBind();
Now my drop-down has values: Section1,Section2,Section3
Problem is:
I have another drop-down drpSubSection. Now i want to fill this drop-down whatever i have selected in the drpSectionType.
for ex If I selected Section1 in drpSectionType then drpSubsection should contain the value
TestA,TestB. Like this:
protected void drpSectionType_SelectedIndexChanged(object sender, EventArgs e)
{
string strType = drpSectionType.SelectedValue;
drpSubsection.DataSource = Enum.GetNames(typeof());
drpSubsection.DataBind();
}
Here typeof() is expecting the enum.But i am getting selected value as string. How can i achieve this functionality.
Thanks
What if you reference an assembly that contains another enum with a value named Section1?
You'll just have to try all the enums you care about, one at a time, and see which one works. You'll probably want to use Enum.TryParse.
Something like this might work, but you have to do some exception handling:
protected void drpSectionType_SelectedIndexChanged(object sender, EventArgs e)
{
string strType = drpSectionType.SelectedValue;
EnmSection section = (EnmSection)Enum.Parse(typeof(EnmSection), strType);
drpSubsection.DataSource = Enum.GetNames(typeof(section));
drpSubsection.DataBind();
}
This might be a bit over the top but it would work if you bind bind Arrays of IEnumItem to your drop down and set it up to show their display text.
public interface IEnumBase
{
IEnumItem[] Items { get; }
}
public interface IEnumItem : IEnumBase
{
string DisplayText { get; }
}
public class EnumItem : IEnumItem
{
public string DisplayText { get; set; }
public IEnumItem[] Items { get; set; }
}
public class EnmSections : IEnumBase
{
public IEnumItem[] Items { get; private set; }
public EnmSections()
{
Items = new IEnumItem[]
{
new EnumItem
{
DisplayText = "Section1",
Items = new IEnumItem[]
{
new EnumItem { DisplayText = "TestA" },
new EnumItem { DisplayText = "TestB" }
}
},
new EnumItem
{
DisplayText = "Section2",
Items = new IEnumItem[]
{
new EnumItem { DisplayText = "Test1" },
new EnumItem { DisplayText = "Test2" }
}
}
};
}
}
drpSubsection.DataSource = Enum.GetNames(Type.GetType("Your.Namespace." + strType));
If the enums are in another assembly, (i.e. they're not in mscorlib or the current assembly) you'll need to provide the AssemblyQualifiedName. The easiest way to get this will be to look at typeof(Section1).AssemblyQualifiedName, then modify your code to include all the necessary parts. The code will look something like this when you're done:
drpSubsection.DataSource = Enum.GetNames(Type.GetType("Your.Namespace." + strType + ", MyAssembly, Version=1.3.0.0, Culture=neutral, PublicKeyToken=b17a5c561934e089"));

Unable to edit values in a DataGridView (using BindingList)

It seems that, due to an unknown cause, I am now unable to edit anything in my DataGridView. The DGV's ReadOnly property value is false, and all columns except for one all have the ReadOnly property set to false as well.
I'm beginning to think that it may be due to a special value I tried adding to one of my classes, one that I only wanted to be modified within the class, but still read only to the public. I don't think that value is messing with anything else, but none the less, here is the relevant portion of my code:
private void loaderWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
loadingBar.Value = e.ProgressPercentage;
if (e.UserState != null)
{
savefiles.Add((SaveFile)e.UserState);
}
}
Where savefiles is a BindingList, and where SaveFile is my class:
public class SaveFile
{
private string d_directory;
private int d_weirdnumber;
private bool d_isautosave;
private string d_fullname;
private string d_datatype;
private string d_owner;
private bool d_isquicksave;
private string d_title;
private string d_gametime;
public SaveFile() { }
public SaveFile(string directory, int weirdnumber, bool isautosave, string fullname, string datatype, string owner, bool isquicksave, string title)
{
d_directory = directory;
d_weirdnumber = weirdnumber;
d_isautosave = isautosave;
d_fullname = fullname;
d_datatype = datatype;
d_owner = owner;
d_isquicksave = isquicksave;
d_title = title;
}
public string Gametime
{
get { return d_gametime; }
}
public string Datatype
{
get { return d_datatype; }
set { d_datatype = value; }
}
public string Title
{
get { return d_title; }
set { d_title = value; }
}
public bool IsQuickSave
{
get { return d_isquicksave; }
set { d_isquicksave = value; }
}
public bool IsAutoSave
{
get { return d_isautosave; }
set { d_isautosave = value; }
}
public string Directory
{
get { return d_directory; }
set { d_directory = value; }
}
public string FullName
{
get { return d_fullname; }
set
{
d_fullname = value;
string[] split = value.Split(new char[]{'-'});
foreach (string str in split)
{
if (System.Text.RegularExpressions.Regex.IsMatch(str, "^\\d\\d:\\d\\d:\\d\\d$"))
{
d_gametime = str;
}
}
}
}
public int Weirdnumber
{
get { return d_weirdnumber; }
set { d_weirdnumber = value; }
}
public string Owner
{
get { return d_owner; }
set { d_owner = value; }
}
}
Gametime is that special property I mentioned earlier. It doesn't have a set function, but according to this, I should be in the clear, right?
Can anyone then tell me why I may not be able to edit any of the DGV cells?
EDIT: I just found out that not setting AutoGenerateColumns to false allows me to edit again, but I still don't know why.
After several hours, a friend finally took a look at it over Remote Desktop. He wrote a function to force all columns to have a non read-only status, and go figure, it worked. So we looked at the column properties in the editor, and somehow... I don't know why... they were all set to Read only. I swear I checked them 4 times before.
The lesson of this story (I guess): When in doubt, check your settings. When not in doubt, become doubtful. Otherwise, file a bug report to Microsoft :\

Categories