This is an Advanced UI SDK for developing finger-friendly Application UIs.
The reason for developing this SDK was mainly to learn about programming for Windows Mobile and the Compact Framework 3.5. I also developed this SDK because I could not find good UI controls that gave total display control to the programmer while taking care of all of the Physics, windowing, and frame buffering AND was open source.
Finally, this SDK was originally developed as part of the XDAFacebook application that I am currently developing.
I am releasing this SDK and its source so that people can have a good foundation to build finger-friendly Windows Mobile applications, and so that programmers starting off in the Windows Mobile world won't have to start from scratch when creating useful UI Controls.
Here are some of the features and uses of this SDK.
Features:
Fully customizable
Easily create custom UI Controls
Resolution independent
Full physics for rendering smooth scrolling
Uses:
Quickly create UI controls
Develop full UI SDKs
Learn basic UI programming for .net CF 3.5
I ask that if you use these controls, please provide feedback so that everyone can benefit!
Thank you and I hope you find these controls useful!
SDK Documentation
Even though the controls are easy to implement, they can seem intimidating at first. Here is an over-view of the core pieces to the SDK:
The IXFItem Interface:
Here are Properties of the interface
PHP:
XFPanelBase Parent { get; set; } // The item's List container
XFItemState State { get; set; } /* An Enum to describe the current item's state
This could include things like [B]Selected[/B] or [B]Normal[/B]*/
Bitmap Buffer { get; set; } // This is the item's cache buffer. Allows for speedy rendering
XFItemStyle Style { get; set; } // CSS like style object. Allows for easy customization
XFItemType ItemType { get; set; } /* Enum to label the type of the current object.
For example, [B]Clickable[/B] or [B]Display[/B] meaning the item won't change*/
The following are the methods that need to be implemented
PHP:
int GetHeight(); /* This returns the height of the item. This value is usually calulated
but in some instances is static. The value should be cached because this method
is called several times during the rendering process.*/
void ResetHeight(); // What ever needs to be done to reset the height cache
void ItemPaint(Graphics g, int x, int y); // Where the magic happens. More on this later
XFItemClickResult GetClickResult(); // An enum is return with what the action of clicking this item was.
The main part of the interface is the ItemPaint method. This method is called from the XFPanelList and passes a Graphics object created from the Buffer Bitmap of the Item. In this method, you do all of your graphics logic, drawing it with the supplied graphics object. The x and y are any offset numbers that should influence when the objects are based. Most of the time, these numbers will be 0, 0.
Because the programmer has total control over how the item is rendered, special care must be used when creating the items, to draw all the features with respect to the XFItemStyle object. This object usually is created in CTOR. An example of the XFItemStyle object being created in one of the SenseUI XFItem's CTORs:
PHP:
public SenseItem()
{
ItemType = XFItemType.Clickable;
Style = new XFItemStyle()
{
BoarderBottomColor = Color.FromArgb(189, 182, 189),
DashStyleBottom = System.Drawing.Drawing2D.DashStyle.Dash,
TextColor = Color.Black,
TextFont = new Font(FontFamily.GenericSansSerif, 8, FontStyle.Regular),
SelectedTextFont = new Font(FontFamily.GenericSansSerif, 8, FontStyle.Regular),
SecondaryTextFont = new Font(FontFamily.GenericSansSerif, 7, FontStyle.Regular),
SelectedSecondaryTextFont = new Font(FontFamily.GenericSansSerif, 7, FontStyle.Regular),
SecondaryTextColor = Color.FromArgb(57, 52, 57),
SelectedTextColor = Color.White,
SelectedBackgroundColor = Color.FromArgb(43, 36, 43),
SelectedSecondaryTextColor = Color.FromArgb(182, 178, 182),
Padding = 11,
PaddingBottom = 12,
PaddingLeft = 10,
PaddingRight = 16
};
}
You will also notice that the ItemType is also set here.
How you use the Style is a little more involved. In the ItemPaint, the programmer should base all of the features off of what is in the Style object. Here is an example of how the above Style object was used in the ItemPaint method:
PHP:
public void ItemPaint(Graphics g, int x, int y)
{
int width = Parent == null ? Screen.PrimaryScreen.WorkingArea.Width : Parent.Width;
XFControlUtils.DrawBoarders(Style, g, 0, 0, width, GetHeight());
int currX = Style.PaddingLeft;
int currY = Style.PaddingTop;
int mHeight = 0;
int sHeight = 0;
if (Icon != null)
currX += _iconSize + Style.PaddingLeft;
SizeF mText = new SizeF();
if (!string.IsNullOrEmpty(MainText))
{
mText = XFControlUtils.GetEllipsisStringMeasure(width - currX - Style.PaddingRight, MainText, Style.TextFont);
MainText = XFControlUtils.EllipsisWord(width - currX - Style.PaddingRight, MainText, Style.TextFont);
}
SizeF sText = new SizeF();
if (!string.IsNullOrEmpty(SecondaryText))
{
sText = XFControlUtils.GetEllipsisStringMeasure(width - currX - Style.PaddingRight, SecondaryText, Style.SecondaryTextFont);
SecondaryText = XFControlUtils.EllipsisWord(width - currX - Style.PaddingRight, SecondaryText, Style.SecondaryTextFont);
}
mHeight = (GetHeight() / 2) - ((int)mText.Height / 2);
if (!string.IsNullOrEmpty(SecondaryText))
{
mHeight = (GetHeight() / 2) - _textSpace - (int)mText.Height;
sHeight = (GetHeight() / 2) + _textSpace;
}
if (State == XFItemState.Selected)
{
XFControlUtils.DrawBackgroundSelected(Style, g, x, y, width, GetHeight());
if (!string.IsNullOrEmpty(MainText))
using (SolidBrush b = new SolidBrush(Style.SelectedTextColor))
g.DrawString(MainText, Style.SelectedTextFont, b, currX, mHeight);
if (!string.IsNullOrEmpty(SecondaryText))
using (SolidBrush b = new SolidBrush(Style.SelectedSecondaryTextColor))
g.DrawString(SecondaryText, Style.SelectedSecondaryTextFont, b, currX, sHeight);
}
else
{
if (!string.IsNullOrEmpty(MainText))
using (SolidBrush b = new SolidBrush(Style.TextColor))
g.DrawString(MainText, Style.TextFont, b, currX, mHeight);
if (!string.IsNullOrEmpty(SecondaryText))
using (SolidBrush b = new SolidBrush(Style.SecondaryTextColor))
g.DrawString(SecondaryText, Style.SecondaryTextFont, b, currX, sHeight);
}
if (Icon != null)
XFControlUtils.DrawAlphaFirstPix(g, Icon, Style.PaddingLeft, Style.PaddingTop);
}
That is as complex as it gets. Other than doing normal Event Handling for ClickReturns, this is all that is required to create beautiful UI Controls for your application.
I hope that this helps! Feel free to PM me or post a reply if you need further clarification.
Class List
Form Controls:
XFPanelContainer - The main control that interacts with the Form.
XFPanels:
XFPanelBase - Basic building block. Handles most of the generic functionality
XFPanelList - Can add IXFItem items.
XFPanelHeader - The top header bar for an XFPanelContainer
XFItems
IXFItem - Interface that all XFItems inherate
XFItemSimpleText - Simple item that displays text
XFItemBack - Special item that allows a panel to slide back
XFItemLoading - Item that allows for work to be down in the background.
XFControlUtils: Library of static, useful utilities for this SDK
DrawAlpha - Draws an image with a supplied Graphics object with a specific level of opacity
DrawAlphaFirstPix - Draws an image and renders all pixels that are the same color as pixel (1,1) are 100% transparent
DrawJustifiedString - draws a justified string
GetEllipsisStringMeasure - Takes a string and if it is more than the supplied width, clips the string and adds a trailing "..." at the end
EllipsisWord - same as the GetEllipsisStringMeasure, except it ellipsis at the words and not at the char level.
GetSizedString - Takes a string and adds "\n" so that the string wraps according to the supplied width
Many Others!
Sense UI Example
Here is a working example. I made this Sense UI example in about 3 hours 15 hours. It isn't complete but gives a good example of how to/why use this SDK. There are 3 screenshots of what this demo looks like.
I'll explain some of the pieces of code when I get some time later today.
The other great example of how to use this SDK is the XFAFacebook Application.
The source for this project is located @ http://code.google.com/p/xda-winmo-facebook/source/browse/#svn/trunk/XFSenseUI
There are a few screenshots of the XDAFacebook application included.
Finally, a quick start tutorial.
Start a new Smart Device project.
Add a reference to the XFControls.dll
Place the following lines of code in the Form1 constructor (after the InitializeComponent()
Code:
XFPanelContainer container = new XFPanelContainer();
container.Dock = DockStyle.Fill;
Controls.Add(container);
XFPanelList list = new XFPanelList();
container.SetMainPanel(list);
list.ShowScrollbar(true);
for (int i = 0; i < 50; i++)
{
list.Add("This is item " + i);
}
Run the project and you will get an output like the "SimpleText.png"
It's that easy!
UPDATE: I've added the XFSense to the Google Code page and have made some pretty extensive updates to it. I've added a few controls including sliders, toggles, checkboxes and radio buttons. It still isn't complete but I will be working to make it a full fledge Sense SDK.
Stay tuned!
Releases:
Initial Release - 9/1/10
When major updates occur, the DLLs will be posted here. The best thing to do is pull the source from the Google Code page and use that.
This will guarantee the freshes code will be used for your projects
Instructions:
Download and unzip the latest XFControls.zip from below.
Add the .dll as a reference.
Program!
The source can be found at: http://code.google.com/p/xda-winmo-facebook/source/browse/#svn/trunk/XDAFacebook/XFControls
List of downloads:
10/6/10 - Updated for speed and better scrolling! - XFControls 0.2.zip
9/1/10 - Initial upload - XFControls 0.1.zip
Other things I might have missed
Reserved Other
Sounds interesting! Definitely looking forward to some screenshots.
kliptik said:
Sounds interesting! Definitely looking forward to some screenshots.
Click to expand...
Click to collapse
Screenshots are up!
Only 3 downloads?! Hmmm.... I figured more people would be interested in a finger-friendly and open source UI SDK...
Is there something wrong with my posts? Are they too confusing?
Let me know what I can do to help! This has taken me a good deal of time to write and I would hope that it would be of use to someone else...
joe_coolish said:
Only 3 downloads?! Hmmm.... I figured more people would be interested in a finger-friendly and open source UI SDK...
Is there something wrong with my posts? Are they too confusing?
Let me know what I can do to help! This has taken me a good deal of time to write and I would hope that it would be of use to someone else...
Click to expand...
Click to collapse
Just DL'd a copy. I'm super swamped at the moment trying to get the next release of KD-Font out, but I'll try and check this out when I get a chance.
Thank you for your contribution!
I will definitely give this a test run at some point. Good work!
you have to add you own graphics to this sdk?
janneman22 said:
you have to add you own graphics to this sdk?
Click to expand...
Click to collapse
yes, this is a UI SDK. it is used to create user controls. The core code handles all the caching and physics, but the programmer must create the actual controls. including the graphics. look at the sense UI example to see how you can implement your own custom UI controls. like i said in the post, it only took about 3 hours to create those controls. most of which was spent creating graphics.
joe_coolish said:
yes, this is a UI SDK. it is used to create user controls. The core code handles all the caching and physics, but the programmer must create the actual controls. including the graphics. look at the sense UI example to see how you can implement your own custom UI controls. like i said in the post, it only took about 3 hours to create those controls. most of which was spent creating graphics.
Click to expand...
Click to collapse
oh right. but does it place controls in the toolbox, or have you to create the controls hard coded?
i could help you to make some grapics packages for this sdk
Ok, I've updated the binaries to be the latest and greatest. The scrolling is super smooth and things are starting to look pretty good!
I also will be updating the XFSense and I'll probably be extending it a little more because I plan on bringing it into the XDA Facebook app.
As always, let me know what you think!
EDIT: Oh, and to answer the question about adding objects to the toolbox, I have not added the OCX files (or whatever they are) so that they can be added to the tool box. But, after you've added the container and the panels, everything is logic after that, so adding the items to the toolbox really doesn't benefit too much.
As far as graphics, I would love help with graphics! Send me a PM and we'll talk!
joe_coolish said:
Here is a working example. I made this Sense UI example in about 3 hours. It isn't complete but gives a good example of how to/why use this SDK. There are 3 screenshots of what this demo looks like.
I'll explain some of the pieces of code when I get some time later today.
The other great example of how to use this SDK is the XFAFacebook Application.
The source for this project is located @ http://code.google.com/p/xda-winmo-facebook/source/browse/
There are a few screenshots of the XDAFacebook application included.
Finally, a quick start tutorial.
Start a new Smart Device project.
Add a reference to the XFControls.dll
Place the following lines of code in the Form1 constructor (after the InitializeComponent()
Code:
XFPanelContainer container = new XFPanelContainer();
container.Dock = DockStyle.Fill;
Controls.Add(container);
XFPanelList list = new XFPanelList();
container.SetMainPanel(list);
list.ShowScrollbar(true);
for (int i = 0; i < 50; i++)
{
list.Add("This is item " + i);
}
Run the project and you will get an output like the "SimpleText.png"
It's that easy!
Click to expand...
Click to collapse
Very nice control. I downloaded the sample (had problem with missing XFControl project but downloaded it from code.google).
Have a couple questions, how would i go about adding image to a child panel?
What I'm trying to so is have about 75 items on the main screen and each item will have sub-panel, when clicking on sub-panel I need to have label x2 and image.
Also when compiling the project I get error:
"Error 1 'XFControls.XFPanels.XFPanelHeader' does not contain a definition for 'BackgroundImage' and no extension method 'BackgroundImage' accepting a first argument of type 'XFControls.XFPanels.XFPanelHeader' could be found (are you missing a using directive or an assembly reference?) C:\downloads\C#\XFSenseUI\XFSenseUIDemo\Form1.cs 39 24 XFSenseUIDemo"
Alright, I'll post an example if I get some time in a bit. But as for the error, it is because the Core XFControls has been modified since the last time I updated this thread. You can download the freshes code from the google code page or use the attached DLL. I'd suggest the Google Code page, since it gets updated more frequently. But then you get all the XDAFacebook with it, so it can also be negative.
Basically to add an image to an XFItem to be added to the XFPanelList, you can either create your own item by inheriting from the IXFItem and doing all the image manipulation in the ItemDraw() method.
For an example of how to do that, look at the XFItemImageDisplay item in the XFControls.XFPanels.XFPanelItems namespace.
If you need something specific, let me know and I'll see if I can whip up an example
I'm new to C# and the compact framework so sample would be good...
Thanks
JarekG said:
I'm new to C# and the compact framework so sample would be good...
Thanks
Click to expand...
Click to collapse
Ok, could you describe how you want the control to look? Also, what you want to supply to the constructor? IE a path for an image, upper text, lower text, maybe even some style things. ETC
Related
Hi gents.
I want to ask you,how can I use external font loaded from ttf file in my app,developed under Embedded Visual C++?
I need to easily change color and size of the font and using the DrawText() function make an output into current DC.
Can someone make an example for me please?
Thank you.
Here's the bare bones of it ,you'll have to flesh it out to suit. It might not be perfect but it works.
Global Variable
Code:
HFONT g_hfont;
Forward declaration of EnumFontProc()
Code:
int CALLBACK EnumFontsProc(LOGFONT *lplf, TEXTMETRIC *lptm, DWORD dwType, LPARAM lpData);
In WM_PAINT print it out. I'll use Wingdings. The name in the EnumFonts must match the actual name of the font as declared in the TTF file.
Code:
case WM_PAINT:
RECT rt;
hdc = BeginPaint(hWnd, &ps);
GetClientRect(hWnd, &rt);
EnumFonts(hdc,TEXT("Wingdings"),(FONTENUMPROC) EnumFontsProc,NULL);
SelectObject(hdc,g_hfont);
DrawText(hdc,TEXT("12345"),5, &rt, DT_SINGLELINE | DT_VCENTER | DT_CENTER);
DeleteObject(g_hfont);
EndPaint(hWnd, &ps);
break;
In EnumFontsProc set the font to the first font given. Returning 0, ends the enumeration, non zero, give me the next.
To change the size do it here by changing lplf->lfHeight and lplf->lfWidth
Code:
int CALLBACK EnumFontsProc(LOGFONT *lplf, TEXTMETRIC *lptm, DWORD dwType, LPARAM lpData)
{
g_hfont = CreateFontIndirect(lplf);
return 0;
}
To load and release your font add the code below to the message handling sections.
Code:
WM_CREATE:
AddFontResource(TEXT("\\Storage Card\\myfont.TTF"));
WM_DESTROY:
RemoveFontResource(TEXT("\\Storage Card\\myfont.TTF"));
Here's the proof it works, (with Wingdings anyway!)
Thanks man,I will try it ASAP.
Well,is it possible to read the ttf file directly from exe resource also?
I am still learning C++,so some things are a bit unclear for me. Can you please post this source?
This stuff is explained fully at:
http://msdn.microsoft.com/en-us/library/aa911455.aspx
I've just taken a few shortcuts with it.
The zip file contains the main .cpp file of the above project. It does not include the AddFontResource or RemoveFontResource statements.
Create a shell WinMo application and replace the main program .cpp file with it.
AddFontResource can only accept the path to a True Type font TTF file as an argument.
The thing you have got to get your head around are CALLBACK routines, they are used during most enumeration routines, and are widely used in Win32 for all sorts of things. A Win32 app's WndProc it itself a callback routine. In the case of EnumFonts, you pass the address of the callback routine to the enumerating function, which will call your function once for every instance it finds that matches your request. You terminate the sequence by returning 0 or it will carry on until there are no instances left. You have to decide what to do with the results. In my case I take the first Wingding font I'm offered, then quit.
Be aware that there is little, or no error handling in this code. I cobbled it together pretty quickly to prove the point.
I remember reading somewhere that if you drop the .TTF file in the Windows directory, and do a soft reset, then Windows will pick it up as a resident font, so the AddFontResource and RemoveFontResource functions are not required. EnumFonts() should know about it, and present it accordingly.
Well,thank you very much for that,but can you please provide me full project source,including all the files? With working project,I can better understand the font loading principle.
Unfortunately,I am too busy nowadays to discover something,that I don't understand well,so every time save is a big plus for me. Thank you very much again.
Attached,
But, it is a VS 2008 Smart Device project. EVC won't read it.
You will have to create a shell hello world project in EVC and copy the modified code in the panels above from TestFont.CPP.
Hello.
Actually i've got it working,but I still cannot discover,how to resize the font.
Where should I exactly put the lfWidth and lfHeight?
I am now a bit confused of that.
This is my code:
Functions and declarations of HFONT,CALLBACK,WM_CREATE,WM_DESTROY are present as you described.
void ShowNumber(HDC hdc, int Value,int xrect,int yrect,int wrect,int hrect,HBITMAP source)
{
EnumFonts(hdc,TEXT("Sam's Town"),(FONTENUMPROC) EnumFontsProc,NULL);
SelectObject(hdc,g_hfont);
TCHAR szText[MAX_LOADSTRING];
int width,height;
rtText.right=wrect;rtText.bottom=hrect;width=wrect-xrect;height=hrect-yrect;
TransparentImage(hdc,xrect,yrect,width,height,source,xrect,yrect,width,height,RGB(255,0,255));
SetBkMode(hdc,TRANSPARENT);
if(Value<10) wsprintf (szText, TEXT ("0%d"),Value);else wsprintf (szText, TEXT ("%d"),Value);
rtText.left=xrect ;rtText.top=yrect ;SetTextColor(hdc,RGB(0,0,0)); DrawText(hdc,szText,2,&rtText,DT_SINGLELINE | DT_LEFT | DT_TOP);
DeleteObject(g_hfont);
}
int CALLBACK EnumFontsProc(LOGFONT *lplf, TEXTMETRIC *lptm, DWORD dwType, LPARAM lpData)
{
g_hfont = CreateFontIndirect(lplf);
return 0;
}
Click to expand...
Click to collapse
This doesn't work:
lplf.lfWidth=0;
g_hfont = CreateFontIndirect(lplf);
Click to expand...
Click to collapse
Actually I want to put one more parameter into ShowNumber() function,which will tell the function the size of the font.
You are nearly there...........
The code to set the font size will have to go in here.......
Code:
int CALLBACK EnumFontsProc(LOGFONT *lplf, TEXTMETRIC *lptm, DWORD dwType, LPARAM lpData)
{
lplf->lfHeight=14;
lplf->lfWidth=8;
g_hfont = CreateFontIndirect(lplf);
return 0;
}
Or whatever your values are, I just picked 8 and 14 as examples. If these values are passed as variables to another function above, store them as global variables, and use them here.
As lplf is passed to this function as a pointer to a LOGFONT structure, you have to use the -> operator to access its members. lplf.lfHeight won't work as you mentioned, that is for predeclared or static structures.
These values have to be changed here in the EnumFontsProc() routine before the font is created, as we are passing that pointer to create the font.
Good Luck!!
P.S. While we are here, let's tidy it up a bit.
Replace:
Code:
if(Value<10) wsprintf(szText,TEXT ("0%d"),Value);else wsprintf (szText,TEXT("%d"),Value);
with
Code:
wsprintf(szText, TEXT ("02%d"),Value);
A very big thanks for that.
I am still beginner in C++,so something can look very comic for others.
My beloved programming language is Pascal.
I really didn't think,that -> is an operator,I've just mentioned,you wrote it as something else(something like "to")
You are more than welcome.
Some features in C/C++ are not immediately obvious, but the real battle is fighting your way through the Win32 programming model, trying to get it to do what you want. Sometimes the simplest of things become maddeningly complicated, but the effort to do it properly is usually worth the effort.
Glad you got it working, best wishes, stephj.
Hello a bit later.
First of all,thank your for your explanation and now I am using this method successfuly.
I want to ask you now,if there is a way to get fixed pitch of the font,that is truetype. With standart font I can achieve with this...
lf.lfPitchAndFamily = (tm.tmPitchAndFamily & 0xf0) | TMPF_FIXED_PITCH;
I am using font,that displays numbers in "digital" mode(7-segment display) and I get the number "1" very narrow in comparison with others(actually it is narrow on any kind display,but is displayed on right segments,so "01" has adequate spacing on hard display). Now I get "0l_" instead of "0_l",that's not preferable.
Thanks in advance for reactions.
I don't think there the above method will work as each character has it own width associated with it.
A simpler approach, a bit of a pain, but which should work, is to draw/print the numeric value out one character at a time using DrawText(). Set a RECT structure up to hold the coordinates of the top left and bottom right of the area for each character.
Setting uFormat to DT_RIGHT will force the character to right align in the RECT area, so the '1' should appear correctly. Move the left and right values along a fixed amount for each character. A bit of trial and error will be involved first until you get the values just right.
Good luck, stephj.
Hi there,
I have a ListBox bounded to a query (linq to xml)
Dim CASDAs XDocument = XDocument.Load("./Data/CASD.xml")
Dim CAS_Query As System.Collections.IEnumerable = From query In Cartridge_Doc.Descendants("Cartridges") Order By _
CStr(query.Element("AA")) Descending, CStr(query.Element("AA"))
Select New Cartridge_Data With {.AA1 = CStr(query.Element("AA")), _
.BB1= CStr(query.Element("BB")), _
.CC1 = CStr(query.Element("CC"))}
Me.ListBox_1.ItemsSource = CAS_Query
Now, what I need to do is to select an item and have the option to delete it.
So far, I always got a run-time exception when trying this
Me.ListBox_1.Items.Remove(Me.ListBox_1.SelectedItem)
System.InvalidOperationException was unhandled
Message=Operation not supported on read-only collection.
So far I have tried a lot of options without any luck.
Any help will be greatly appreciated!
Thanks in advance.
Stick your Linq result in an ObservableCollection, bind this to the Listbox and delete the item directly from the underlaying collection.
emigrating said:
Stick your Linq result in an ObservableCollection, bind this to the Listbox and delete the item directly from the underlaying collection.
Click to expand...
Click to collapse
Please, can you poost a little code to do that? I'm fairly new to this collections world.
On the other hand, once the item got deleted, how the Listbox gets refreshed?
Thanks!
You have to set up an NotifyPropertyChanged class to keep the listbox updated with your collection. The default phone list application template that comes with Visual Studio shows you how to do this. I think its's in c# though and it looks like you're coding in VB. I'm sure there's examples in VB you can find on the web with a little searching.
Ren13B said:
You have to set up an NotifyPropertyChanged class to keep the listbox updated with your collection. The default phone list application template that comes with Visual Studio shows you how to do this. I think its's in c# though and it looks like you're coding in VB. I'm sure there's examples in VB you can find on the web with a little searching.
Click to expand...
Click to collapse
My ListBox takes its data from an XML file via query.
Which strategy do you think is the best?
To first delete the Xelement then refresh the ListBox?
Or deleting from the item from the ListBox, then update the XML file?
Sorry but I have all the samples from MS and didn't find any phone list one.
Any code will be greatly appreciated!
Oops. It's called "Windows Phone Databound Application". Attached is a screenshot of the project if it makes it easier for you to find it.
It's hard to post code because I don't know what your xaml looks like and bindings have to be set there for it to work. The best thing you can do is load the above project and play around with it.
You never have to refresh the items in the listbox. A bound listbox updates itself when an item in the collection changes. Change the collection and your listbox will reflect those changes. The NotifyPropertyChanged class is what triggers the listbox to update itself.
I do C#, not VB but the following should give you some idea.
Code:
public class Model : INotifyPropertyChanged
{
public string Title { get; set; }
public string Blurb { get; set; }
public event PropertyChangedEventHandler PropChanged;
public void NotifyPropertyChanged(String _propName)
{
if (null!=PropChanged)
{ PropChanged(this, new PropertyChangedEventArgs(_propName)); }
}
}
The above is your model, create any properties you need there - i.e. one per item of data in your XML file.
Next, you need to create an ObservableCollection somewhere, for the sake of simplicity let's stick it in your MainPage.xaml.cs file for now, so;
Code:
public partial class MainPage : PhoneApplicationPage
{
public ObservableCollection<Model> Items { get; set; }
public MainPage()
{
InitializeComponent();
this.Items = new ObservableCollection<Model>();
MyListBox.ItemsSource = this.Items;
WebClient wc = new WebClient();
wc.OpenReadCompleted += wc_OpenReadCompleted;
wc.OpenReadAsync(new Uri("http://your.server.here/datafile.xml");
}
public void wc_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
using (Stream s = e.Result)
{
XDocument xd = Xdocument.Load(s);
var XMLdata = (from q in doc.Descendants("Item") select new Model()
{
Title = (string)q.Element("Title"),
Blurb = (string)q.Element("Blurb")
}
foreach (Model m in XMLdata)
{
this.Items.Add(m);
}
}
}
public MyListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ListBox lb = (ListBox)sender;
if (lb.SelectedIndex == -1)
return;
this.Items.Remove(lb.SelectedItem)
}
}
This will create a collection named Items as well as tell your ListBox (named MyListBox) to get it's data from said collection. Then it will read (asynchroniously) the XML file from the web and copy each item of data into your collection.
When you select an item in your ListBox it will be deleted from the ObservableCollection which in turn will remove it from the view (ListBox). At this stage you want to include code to also remove this from your actual XML file and so on of course. But the idea is that you work on your Collection only and your View will update based on what is changed - automagically.
Please note, the above code may or may not work out of the box. Written directly here on the forums so it hasn't gone thru VS2010's excellent IntelliSense. Also, the above code is in no way the most efficient way of doing certain things, but it gives you an idea as to what code you need to write to handle your scenario.
While I wrote this I see you've got an answer above which directs you to the VS template - use that and everything should become clear. All you have to remember is that perform operations on the Collection - not directly on the ListBox and you'll be fine.
Emigrating and Ren13B,
Thanks to both of you for the help. Very appreciated!
Will take both advices to see what comes up.
Thanks!
The DllImport Project
This project is part "Real DllImport" and also not the same time. It has limited DllImport to only types "void();" (well isn't that DllImport )
Other CORE functions that require multiple [IN] or/and [OUT] are to complex for the code right now (there are so many possibilities).
Terms of use, using the code (free to use, under my name "fiinix00 @ XDA"~ in app)
As posted to JaxBot
Well thanks for asking, this project is free for everyone, the one purpose it was made for.
The only thing i needed back is my name (fiinix @ XDA) included in whose projects (external) that take use of my code base. There is no licence or something (GNU e.g.), it just make people mad and confused.
So feel free to take advantage of the code whenever you want, just remember, i want my name on it. =D
Click to expand...
Click to collapse
UPDATE @ (2011y-03m-26d - 23:08)
Ohyeah, i can control zune from my application (Resume, Stop, Pause, NextSong, PrevSong, ShutdownZune, StartZune, ... to come)
Turn on/off radio remote from code. (DAMN, the radio begins to play without "No antenna" but no sound, plugin again and it sounds :/)
UPDATE @ (2011-03-27 - 14:35)
- Set clipboard (lol, doesent even have NODO): DllImportCaller.lib.Clipboard_SET("Hello");
- Get clipboard: DllImportCaller.lib.Clipboard_GET(ref [string]);
- Enchanted: Phone.Clipboard.Value { get { ... } set { ... } }
- Basic calls against void without arguments: DllImportCaller.lib.VoidCall( [DLL] , [Method] );
- API for verifying method existence: DllImportCaller.NativeMethodExists( [DLL] , [Method] );
- Raw API for controlling vibrator (unlimited "on", also continues to vibrate on exit, dont forget to turn off ): Phone.Vibrator. { Vibrate(), Stop() }
Source code + test XAP updated (2011-03-27-17:38) (Clipboard GET; is corrupt)
HELLO THERE TASKMANAGER!!
(I can now enumerate the running processes on the phone )
Proof: http://moitox.com/WP7tskMngr.png
Hook to keyboard, for some reason it only show interest in the "Search" button.
Documentation of proc:
[WP7Process].{ CreationTime, ExitTime, KernelTime, UserTime, <-UpdateTimes(), Kill(exitCode), { PROCESSENTRY32 RAW } }
^ for "currentProcess.Kill()" use "Phone.TaskManager.GentlyExitCurrentProcess();" the Kill(exitCode) KILLS
WP7Process[] = Phone.TaskManager.Named("taskhost");
WP7Process = Phone.TaskManager.CurrentProcess();
Documentation of network
- ConnectionType { Unk0, Unk1, Unk2, Connected, Unk3 ... }
- ConnectionType = Phone.Network.GetWirlessState;
Phone.KeyboardHook.IsKeyDown(int key)
> Search = 124 (lol)
Misc finds
DllImportCaller.NativeMethodExists("urlmon", "IsIntranetAvailable");
DllImportCaller.NativeMethodExists("urlmon", "ObtainUserAgentString");
- Code updated! (2011-03-28-22:12)
Added "Phone.DEP", dep is a wrapper against info stored in "Microsoft.Phone.Info.DeviceExtendedProperties"
Full "TaskHost.exe" support
HostInformation = Phone.TaskHost.GetCurrenHostInfo();
HostInformation {
fDehydrating = 0,
fRehydrated = 0,
hHostWnd = -25821178 /* This silverlight managed window (host window) */
szAppDataFolder = "\\Applications\\Data\\8DC5214E-88FA-4C2D-A379-2CD74FE24B72\\Data"
szAppInstallFolder = "\\Applications\\Install\\8DC5214E-88FA-4C2D-A379-2CD74FE24B72\\Install"
szAppIsolatedStorePath = "\\Applications\\Data\\8DC5214E-88FA-4C2D-A379-2CD74FE24B72\\Data\\IsolatedStore"
szProductId = "{8DC5214E-88FA-4C2D-A379-2CD74FE24B72}"
szTaskPage = "MainPage.xaml" /* Current page? */
szUri = "app://8DC5214E-88FA-4C2D-A379-2CD74FE24B72/_default"
ullLastInstanceId = 39 /* fully retarded property? */
}
Code updated! (2011-03-29-23:25)
new Phone functionality
Phone.OS.{ Shutdown(ewxCode) } /* 1.0.2 can still call it with "DllImportCaller.lib.ShutdownOS" (failed tho on mine in 1.0.2) */
Added "GetLastError7" (C++ ::GetLastError()) for better C# side error handling.
Code updated! (2011-04-03-12:37)
Code updated! (2011-04-04-21:48)
- App launcher code!!
- Enchanted IO support
- 1.0.6!
Code updated! (2011-04-05-22:08)
- Enchanted task support
- Console7.Title { get; set; } etc.
Code updated! (2011-04-08-00:03)
- Stable%: 97 :/
- Battery support (see battery info (CORE only))
- Phone.Sound { MasterVolume!! { get; set; }, etc } (controlling phone master volume over all processes)
- Phone.OS.Kernel.ResetDevice(); (instant stops kernel, instant shutdown, not recommended!)
Code updated! (2011-04-09-22:39)
- Enchanted "Phone.Battery" class
- Phone.TaskManager.+GetCurrentProcessId
- WiFi Controll! (On/Off) (from code!)
- Bluetooth Controll! (On/Off) (from code here toe!)
- Phone.OS.+GetSystemStartupItems(),+GetDesktopWindowHandle()
- New class "Phone.Search."+SearchFor,+OpenSearch,+BindSearchButtonToPage (FAILS)
- New class "Phone.XboxLive"+GetIsXboxLiveEnable,+GetIsSignedIn
- Yep: 1.0.9!
Code updated! (2011-04-17-22:01) //damn, not update in 8 days~
- Phone.OS.OSLanguage { SubLanguageID, PrimaryLanguageID }
- Phone.WP7Process.+ CurrentProcessID (int),+GetCurrentProcess() returns guaranteed the right taskhost @class_WP7Process
- Improved Phone.OS.Memory
- + Extra i don't remember (8 days)
Code updated! (2011-05-22-21:25)
- 1.2.1 (because 1.2 methods was commented out to set things right (less crash))
- HUGE improvements
- Removed unneeded **** to speed things up
- Screenshot 161 ms per capture (non-save-to-gallery) =D
- =D
Mango support added(2011-10-26-19:30)
- yep, "ATL" Mango compiled. I have not yet tested to run it on a NoDo.
- Trying to implement a ASM virtual machine; example:
Code:
[ASMMethod(Dll = "coredll", EntryPoint = "GetLastError")]
public delegate int GetLastError();
var last = ASMGenerator.GenerateDelegateFor<GetLastError>();
int code = last();
Custom tile support added(2011-11-07-23:08)
- Custom core tiles ftw!
[/CODE]
Source: Attatchment
-Compile VS2008 folder with C++ compiler from WM6 SDK
-Windows Mobile SDK 6 PRO
-Visual Studio 2010 (+ WP7 Silverlight SDK)
Test-app: Attatchment
-Deploy
-No need anymore to do a initialize button call, automatic called on first use in code "DllImportcaller.lib.cctor" by JIT (Net Framework just in time).
-Do some tests from the scrolling list. (due there are more CORE back-code API's than buttons, all tests can not be tested).
OLDER VERSIONS WILL BE DEPRECATED AND WILL BE REPLACED BY NEWER, MAX ATTACHMENTS IS 8.
fiinix said:
Searched for dllimport but did not found what i was searching for; so i need to ask about if it is possible to do a dllimport with interop in meta?
Because if not, i think i have found something quite the same without dllimport.
Click to expand...
Click to collapse
We can't p/invoke, but only use COM interfaces to interop with native code. What did you find?
Im trying the method, of c++ calling the calls for me.
In c++ i call "HMODULE dll = LoadLibrary("MyDLL.dll");" to get the native kerner32.dll e.g.
Then call "Dword addr = GetProcAddress(dll, "MyMethod");"
Code:
typedef HRESULT (STDAPICALLTYPE * LPFNBOX) (void);
C# -> COM (LoadLibrary e.g.) ->
return dll addr -> return to C#
C# -> COM -> LPFNBOX * val = (LPFNBOX)GetProcAddress(addr, "method"); ->
return val(); ->
return to C#
May work with some privileges bypass, not tested. (^ Not programmer, skip it)
Step 1 of 2 "LoadLibrary7" S_OK (success!)
int result;
var hr = lib.MessageBox7("lpText", "lpCaption", MB.MB_OK, out result);
And: It shows a native msg box
It ** worked!
var t = DllImportCaller.Call<string, string>("coredll.dll", "CeRunAppAtEvent", "emptyArgs");
LoadLibrary7( .. "coredll.dll" .. ) @ -1304248592
GetProcAddress7( .. CeRunAppAtEvent" .. ) @ 1105512120
Now just "box" and call it
Sounds sweet. Any code to share?
kuerbis2 said:
Sounds sweet. Any code to share?
Click to expand...
Click to collapse
Well, last step now is to box it. Due "Compact Framework 3.7" there is no "Marshal.GetDelegateForFunctionPointer". But iw found something quite common.
Code, yes. (if i succeed)
Well, there we go. I did just shut down the phone with code (phone sided code)!
DllImportCaller.lib.ShutdownOS();
nevermind.
So you wrapped LoadLibrary/GetProcAddress via C++/COM, how is this any different than what we have now? It's easier to simply write C++ code and provide a calling mechanism. (Which is what we're doing.)
WithinRafael said:
So you wrapped LoadLibrary/GetProcAddress via C++/COM, how is this any different than what we have now? It's easier to simply write C++ code and provide a calling mechanism. (Which is what we're doing.)
Click to expand...
Click to collapse
The use of dllimports (gdiplus.dll located in "\Windows\" for example) in C# code. And you dont need to know c++/programmer to call c++ methods anymore.
The last annoying, to get that IntPtr (native) to become a managed method... (it is possible). Anyways its going great, i'll continue tomorrow
Hey any code on this?
Flow WP7 said:
Hey any code on this?
Click to expand...
Click to collapse
Very soon (today @ Central European Time, dinner). Due im currently at work. The preview will not do all the way down to dllimport because the last thing for me is to figure out how to call the native IntPtr from c# with c# arguments.
Glad you guys are asking
Yeah, would be really cool if thats possible, then it would be possible todo everything over mscoree.dll, i guess?!
I found something intresting myself yesterday, the mscorlib.dll and System.dll on the phone are different from the ones in the sdk. (They contain a lot more stuff) Also the the mscorlib contains DllImports for almost everything.
If there is some way to get an internal class that would be also a great alternative...
Flow WP7 said:
Yeah, would be really cool if thats possible, then it would be possible todo everything over mscoree.dll, i guess?!
I found something intresting myself yesterday, the mscorlib.dll and System.dll on the phone are different from the ones in the sdk. (They contain a lot more stuff) Also the the mscorlib contains DllImports for almost everything.
If there is some way to get an internal class that would be also a great alternative...
Click to expand...
Click to collapse
Internal's -> typeof(CLASS).GetMethod( ... ).Invoke( ... ). Works perfect with </Interop> in manifest. Else "MethodAccessException".
And all those dllimports in mscore, plenty of them, most doing calls to mscoree
Goad is to do "DllImportCaller.Call( DLL, METHOD, ARGS )"~
I just tried this:
Type type = Type.GetType("System.PInvoke.PAL");
Type type1 = Type.GetType("System.Host.HostNative+FIND_DATA");
object createInstance = Activator.CreateInstance(type1);
And this results into MethodAccessException
I have a WPInteropManifest.xml, so what do you mean by:
Works perfect with </Interop> in manifest. Else "MethodAccessException".
Click to expand...
Click to collapse
regards,
Flow
Flow WP7 said:
I just tried this:
Type type = Type.GetType("System.PInvoke.PAL");
Type type1 = Type.GetType("System.Host.HostNative+FIND_DATA");
object createInstance = Activator.CreateInstance(type1);
And this results into MethodAccessException
I have a WPInteropManifest.xml, so what do you mean by:
regards,
Flow
Click to expand...
Click to collapse
This is going kind of off topic. Stay to topic.
Anyways, Activaror.CreateInstance cannot create internal constructots, you need TYPE.GetConstructor( ... ).Invoke. Check visibility of ctor.
fiinix said:
The last annoying, to get that IntPtr (native) to become a managed method... (it is possible). Anyways its going great, i'll continue tomorrow
Click to expand...
Click to collapse
Having some difficulties (its killing itself on call) :/ Ill publish as fast as possible.
I've been banging my head against this one all morning and now i have a head ache so i decided to stick it out to you lot.
I want to make all my user controls (labels, checkbox's etc) transparent - well the text at least. I found this thread on MSDN but i'll be honest and say i'm not entirely sure what i'm supposed to do with it.
Thanks for your thoughts.
Works a treat. Lifted the code from the site and dropped it straight into the form class.
Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.WindowsCE.Forms;
namespace TestDevApp
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
forum.xda-developers.com/search.php?searchid=90851847
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
DrawLabel(label1,e.Graphics);
DrawLabel(label2, e.Graphics);
DrawLabel(label3, e.Graphics);
DrawLabel(label4, e.Graphics);
}
private void DrawLabel(Label label, Graphics gfx)
{
if (label.TextAlign == ContentAlignment.TopLeft)
{
gfx.DrawString(label.Text, label.Font, new SolidBrush(label.ForeColor), label.Bounds);
}
else if (label.TextAlign == ContentAlignment.TopCenter)
{
SizeF size = gfx.MeasureString(label.Text, label.Font);
float left = ((float)this.Width + label.Left) / 2 - size.Width / 2;
RectangleF rect = new RectangleF(left, (float)label.Top, size.Width, label.Height);
gfx.DrawString(label.Text, label.Font, new SolidBrush(label.ForeColor), rect);
}
else //is aligned at TopRight
{
SizeF size = gfx.MeasureString(label.Text, label.Font);
float left = (float)label.Width - size.Width + label.Left;
RectangleF rect = new RectangleF(left, (float)label.Top, size.Width, label.Height);
gfx.DrawString(label.Text, label.Font, new SolidBrush(label.ForeColor), rect);
}
}
}
}
Devtrans is the view in VS
Transparent is the actual running code.
Cool thanks.
I did try using DrawString but the drawn text doesn't scroll with the form when you... well.... scroll the form.
I'm gonna have the afternoon off but i will check it out properly later. Would this also work for check boxes? If so what are the changes that would need to be made?
Checkboxes might be a different matter. The above method does not work, it only deals with the text caption. There is is an article on The Code Project at
http://www.codeproject.com/KB/dotnet/TransparentControl.aspx
It appears like they have almost created a control from scratch. You may have to take control/override that much of the object, to get it to work, that you have almost created a new control.
stephj said:
Checkboxes might be a different matter. The above method does not work, it only deals with the text caption. There is is an article on The Code Project at
http://www.codeproject.com/KB/dotnet/TransparentControl.aspx
It appears like they have almost created a control from scratch. You may have to take control/override that much of the object, to get it to work, that you have almost created a new control.
Click to expand...
Click to collapse
I did see that page but i couldn't figure out how the hell to use it
Ok, so now you have found one of the BIGGEST challenges to WM development.
I spent 4+ months trying to get the same thing you are looking for (well, what I assume you are looking for), that is: A transparent label that you can use your finger to scroll.
If that is what you are looking for, I can tell you right now that you need to either look into custom controls that already do this or decide how much time you are willing to invest into something as simple as that.
Here is the basic components that you will need to code to get DrawString to properly scroll with your finger:
You will need to code up some kind of container or panel that holds the current virtual x,y coordinates.
You will need to code up some kind of custom control that can be added to the previously made container
Create logic in the container to take the current virtual x,y coords and determine which custom controls are visible and should be drawn on the screen, pass them their offset coords, and draw the control
Override the OnMouse*ACTION* events on the container to manipulate the virtual x,y coords and then refresh the screen
You also will need to know about double buffering so you don't get any flickering.
It's a very very hard thing to do on WinMo, something that other platforms take for granted. This is one of the reasons that some custom WinMo programs have UIs that are either really terrible, or take tons of resources.
If you want to give it a go (and I would highly recommend doing it, I can't tell you how much I learned about software development by creating my own custom controls) I can help point you in the right directions. Feel free to take a look at the code I've written for my Facebook app (specifically the XFControls and SenseUI projects). I'm not on XDA as often as I'd like, but send me a PM with your questions and I'll respond when I log in.
Good Luck!
Hi all,
I recently finished learning how to create an APK using PhoneGap with code written using HTML5, CSS3 and Javascript.
Now, I would like to create a simple database app but I am not sure how to proceed. From what I learned about PhoneGap, everything can only be written in HTML5, CSS and Javascript coding. How do I get information from a database(flat-file or MySQL), display the data and edit it similar to how one would do using Ajax(I currently don't know how to code in ajax)? Is this possible with PhoneGap? How? Do I need a framework like JQuery Mobile to do this?
There would only be one page/view:
- displaying what is in the table
- and editing/adding new data to the table
Thank you.
using frameworks such as jquery mobile is a better option. u can use ajax calls to server to populate data. create a server side code that responds to ajax calls from app and fetch data from my sql and sends back the data either as json or xml
Falen said:
Hi all,
I recently finished learning how to create an APK using PhoneGap with code written using HTML5, CSS3 and Javascript.
Now, I would like to create a simple database app but I am not sure how to proceed. From what I learned about PhoneGap, everything can only be written in HTML5, CSS and Javascript coding. How do I get information from a database(flat-file or MySQL), display the data and edit it similar to how one would do using Ajax(I currently don't know how to code in ajax)? Is this possible with PhoneGap? How? Do I need a framework like JQuery Mobile to do this?
There would only be one page/view:
- displaying what is in the table
- and editing/adding new data to the table
Thank you.
Click to expand...
Click to collapse
If you just want your app to have a local database then HTML5 already does that for you. I've used this library in the past and had no problems with it at all...
http://html5sql.com/
I wrote an app that imported a CSV file into a database. It was a very basic app, written as proof of concept for a bigger project when I first started developing web apps for mobile. Here's a basic version of importing a CSV and using html5sql to create a table with it...
Code:
function createDatabase() {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
}
function gotFS(fileSystem) {
fileSystem.root.getFile("/sdcard/external_sd/temp/PRODUCTS.CSV", null, gotFileEntry, fail);
}
function gotFileEntry(fileEntry) {
fileEntry.file(gotFile, fail);
}
function gotFile(file){
readAsText(file);
}
function readAsText(file) {
var reader = new FileReader();
reader.onloadend = function(evt) {
var csv = evt.target.result;
var lines = csv.split("\n");
var i = 1;
html5sql.openDatabase("com.archer.testapp.db", "Test DB", _dbSize);
html5sql.process("DROP TABLE IF EXISTS products; " +
"CREATE TABLE IF NOT EXISTS products (linecode int, description varchar(255), barcode varchar(25), price int, stock int); ", function() {
function addRow() {
var line = lines[i].split(",");
var sql = "INSERT INTO products (linecode, description, barcode, price, stock) values (" +
line[0] + ", " +
"'" + line[2] + "', " +
"'" + line[1] + "', " +
line[6] + "," +
line[13] + ")";
html5sql.process(sql);
var pd = i / lines.length * 100;
$(".progress-bar").css("width", pd + "%");
i++;
if (i < lines.length) {
setTimeout(addRow, 2);
}
}
addRow();
}, function(error, failingQuery) {
alert("Error : " + error.message + "\r\n" + failingQuery);
});
};
reader.readAsText(file);
}
There's obviously stuff in there that won't be relevant and you'll need to change. Also I had a global variable, _dbSize, that was the initial size (in bytes) of the database, and there's some stuff in there about a progress bar. Use it or delete it - it won't affect the database being created.
Also, note the use of the addRow() function that calls itself. This was to enable the function to run asynchronously, which is needed if you want to be UI friendly (nothing will update whilst doing the import if you just import everything in one go).
However, since you mention AJAX then that may not be relevant. In which case you're just looking at API calls for whatever service is holding your database.
Hi friend ! If you're new to hybrid development, I highly recommend you to take a look at Ionic. It would help you on so many levels ! http://ionicframework.com/
About your issue, you can always define a REST API using your favorite backend (I know it can be done very easily with Laravel framework in PHP using MySQL DB). I prefer using Firebase ! https://www.firebase.com/
Firebase and Ionic framework based on AngularJS are such perfect match that half your code is already done before you knows it.
Happy coding !