Can someone please give me an example how to bind enum to listpicker on Windows Phone 8?
Can't find any on the internet... and the lack of documentation regarding this toolkit won't help.
Thanks
Binding that is easy. The only problem is that the extension method GetNames() is not available in windows phone. However, you can write one.
public static class EnumExtensions {
public static IEnumerable<string> GetNames<TEnum>() where TEnum : struct {
var type = typeof(TEnum);
if (!type.IsEnum)
throw new ArgumentException(String.Format("Type '{0}' is not an enum", type.Name));
return (
from field in type.GetFields(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static)
where field.IsLiteral
select field.Name)
.ToList<string>();
}
}
Once you have that it is easy to bind it to any list.
public enum MyEnum {
v1, v2, v3
}
// Binding
myListPicker.ItemsSource = EnumExtensions.GetNames<MyEnum>();
// Getting selected value
var myEnum = (MyEnum)Enum.Parse(typeof(MyEnum), myListPicker.SelectedItem.ToString());
Related
A Enum is coming back from the service layer with 1 out of 4 options and am using a case statement to handle it in my web code. I thought that I will be doing this at several places and to have some design pattern in place. Now based on each value from Enum I am doing is returning a string . creating a class for each enum seems to be a overkill. what is the best way to handle this
You don't need to create a new subclass for each enum value, you can have multiple instances of the same class, one for each value:
public class MyEnumType {
private readonly string value;
private MyEnumType(string value) {
this.value = value;
}
public string Value {
get { return value; }
}
public static readonly MyEnumType ValueA = new MyEnumType("foo");
public static readonly MyEnumType ValueB = new MyEnumType("bar");
...
}
I'm having an issue trying to resolve named components. Per the Castle documentation, it states that when more than one components have the same dependency, the first registered component is chosen first. Register more components for the same service
To avoid that, I use named components to resolve them for the same dependency.
container.Register(Component.For<DataContext>().ImplementedBy<MyContext>()
.Named("Db1").DependsOn(Property.ForKey<string>()
.Eq(Configuration.ConnectionStrings["Db1"].ConnectionString)));
container.Register(Component.For<DataContext>().ImplementedBy<MyContext>()
.Named("Db2").DependsOn(Property.ForKey<string>()
.Eq(Configuration.ConnectionStrings["Db2"].ConnectionString)));
and then call kernel.Resolve<DataContext>(cbo.SelectedItem.ToString()); where cbo is a ComboBox conrtol, I always get the first component registered no matter which option is selected.
This was too much to put in a comment. Windsor version 3 supports what you want to do. Here's what I tried and it worked:
public interface IFoo
{
string Name { get; }
}
public class Foo : IFoo
{
private readonly string item;
public Foo(string item) { this.item = item; }
public string Name { get { return this.item; } }
}
[TestMethod]
public void TestMethod1()
{
var container = new WindsorContainer();
container.Register(Component.For<IFoo>().ImplementedBy<Foo>().Named("F1").DependsOn(Property.ForKey<String>().Eq("one")));
container.Register(Component.For<IFoo>().ImplementedBy<Foo>().Named("F2").DependsOn(Property.ForKey<String>().Eq("two")));
var f1 = container.Resolve<IFoo>("F1");
var f2 = container.Resolve<IFoo>("F2");
}
The variable f1 referenced the instance with the item of "one" and f2 referenced the instance with the item of "two". Could you create a failing test case that highlights your issue?
please, how to work with enums in Entity Framework code first. i want that in my class "Annonce" i can have this proprety
public Status EtatAnnonce { get; set; }
and Status is defined like this
public enum Status
{
Pending,
Approved
}
You need to create a converter field to store the value as int in the database.
public int MyEnumValueInt {get;set;}
[NotMapped]
public MyEnum MyEnumValue
{
get{ return (MyEnum)MyEnumValueInt;
set{ MyEnumValueInt = (int)value;
}
Note: The enum support will be improved in EF 5.
Will point you towards
EF5 does not create enum columns
To give a summary of enum support in Entity Framework code first:
EF4: Not supported
EF5: only supported if you are targeting .net framework 4.5 and higher
EF6: only supported if you target .net 4.0 and higher
Cheers!
I've answered two questions regarding Enums in EF; these should help you along:
Enums with EF code-first - standard method to seeding DB and then using?
and
EF 4.1 Code First - map enum wrapper as complex type
You can use private properties in your model to map your data to whatever property type you want.
// Model
public class Piece
{
// Subclass Piece to add mappings for private properties
public class PieceConfig : EntityTypeConfiguration<Piece>
{
public PieceConfig()
{
Property(b => b.dbtype); // needed for EF to see the private property
}
}
[Column("type", TypeName = "VARCHAR")]
private string dbtype { get; set; }
[NotMapped]
public PIECE type
{
get { return (PIECE)Enum.Parse(typeof(PIECE), dbtype); }
set { dbtype= value.ToString(); }
}
}
Then you just need to add the configuration to your OnModelCreating method
modelBuilder.Configurations.Add(new Piece.PieceConfig());
How to cast Java.Lang.Object to some native type?
Example:
ListView adapter contains instances of native type Message. When i am trying to get SelectedItem from ListView it returns instance of Message type casted to Java.Lang.Object, but I can't find solution to cast Java.Lang.Object back to Message.
var message = (Message)list.SelectedItem;
// throws Error 5 Cannot convert type 'Java.Lang.Object' to 'Message'
Please Help.
After long time debuging, have found the solution:
public static class ObjectTypeHelper
{
public static T Cast<T>(this Java.Lang.Object obj) where T : class
{
var propertyInfo = obj.GetType().GetProperty("Instance");
return propertyInfo == null ? null : propertyInfo.GetValue(obj, null) as T;
}
}
Usage example:
var message = list.GetItemAtPosition(e.Position).Cast<Message>();
bundle.PutInt("Message", message.ID);
After careful sdk study have found MonoDroid integrated extension for this purpose:
public static TResult JavaCast<TResult>(this Android.Runtime.IJavaObject instance)
where TResult : class, Android.Runtime.IJavaObject
Member of Android.Runtime.Extensions
The least magical way of getting a native type from the Spinner is to call
message = ((ArrayAdapter<Message>)list.Adapter).GetItem(list.SelectedItemPosition);
I used this code from above answer and it works fine to me
public static class ObjectTypeHelper
{
public static T Cast<T>(this Java.Lang.Object obj) where T : class
{
var propertyInfo = obj.GetType().GetProperty("Instance");
return propertyInfo == null ? null : propertyInfo.GetValue(obj, null) as T;
}
}
and this is how I used
var selectedLocation = locationSpinner.SelectedItem.Cast<Location>();
I am able to get my location object fine from spinner
For generic collections, the right answer would be to use JavaList, which is a Java.Lang.Object and also implements IList. But it involves more work that's for sure. This is actually just an adapter for Java's ArrayList implementation.
You could always try the JavaCast<> method (most of the views implement this)(not tested):
var message = list.SelectedItem.JavaCast< Message >();
If for some reason GetChildAtPosition is not possible, serialise the object to json string and then deserialise the string back to native class.
All of the above answers are correct but I found the simplest way for my case was to make the object a subclass of Java.Lang.Object.
For example I'm writing a Android app in Monotouch, mimicking the concept of a UITableView in iOS using the ExpandableListAdapter, which requires the equivalent of UITableViewCells, so I subclassed cell objects from Java.Lang.Object allowing me to implement a subclass of ExpandableListAdapter such as
public override Java.Lang.Object GetChild(int position, int childPosition)
Etc.
it's work for me:
public class HolderHelper<T> : Java.Lang.Object {
public readonly T Value;
public HolderHelper (T value)
{
this.Value = value;
}
}
test:
chkFileName.Tag = new HolderHelper<LinkInfo> (item);
LinkInfo link= (chkFileName.Tag as HolderHelper<LinkInfo>).Value;
Hey there! I'm trying to write a POCO class in proper F#... But something is wrong..
The C# code that I want to "translate" to proper F# is:
public class MyTest
{
[Key]
public int ID { get; set; }
public string Name { get; set; }
}
The closest I can come to the above code in F# is something like:
type Mytest() =
let mutable _id : int = 0;
let mutable _name : string = null;
[<KeyAttribute>]
member x.ID
with public get() : int = _id
and public set(value) = _id <- value
member x.Name
with public get() : string = _name
and public set value = _name <- value
However when I try to access the properties of the F# version it just returns a compile error saying
"Lookup on object of indeterminate type based on information prior to this program point. A type annotation may be needed prior to this program point to constrain the type of the object. This may allow the lookup to be resolved."
The code thats trying to get the property is a part of my Repository (I'm using EF Code First).
module Databasethings =
let GetEntries =
let ctx = new SevenContext()
let mydbset = ctx.Set<MyTest>()
let entries = mydbset.Select(fun item -> item.Name).ToList() // This line comes up with a compile error at "item.Name" (the compile error is written above)
entries
What the hell is going on?
Thanks in advance!
Your class definition is fine, it's your LINQ that has a problem. The Select method is expecting an argument of type Expression<Func<MyTest,T>> but you're passing it a value of type FSharpFunc<MyTest,T> - or something similar to that anyway.
The point is you can't use F# lambda expressions directly with LINQ. You need to write your expression as an F# Quotation and then use the F# PowerPack to run the code against an IQueryable<> data source. Don Syme has a good overview of how this works.