I need to change the background color several times during one event , currently I am doing this
LayoutRoot.Background = new SolidColorBrush( Colors.Cyan );
and its changing the color.
but I want it to be like this
LayoutRoot.Background = new SolidColorBrush( Colors.Cyan );
System.Threading.Thread.Sleep(2000);
LayoutRoot.Background = new SolidColorBrush( Colors.White );
but the problem that the 2nd piece of code changes directly to white , because the change occurs when the execution is done , I want it to be done while the code is executing , any ideas for that ?
int state;
// Constructor
public MainPage()
{
state = 0;
// create our dispatch timer
DispatcherTimer timer;
timer = new DispatcherTimer();
timer.Interval = TimeSpan.FromMilliseconds(2000);
timer.Tick += OnTimerTick;
timer.Start();
// timer.Stop(); // call this to stop
}
// if the timer is on, cycle the color
private void OnTimerTick(object sender, EventArgs e)
{
try
{
if(state == 0){
LayoutRoot.Background = new SolidColorBrush( Colors.Cyan );
state = 1;
}
else
{
LayoutRoot.Background = new SolidColorBrush( Colors.White );
state = 0;
}
}
catch (Exception ex)
{
string error_message = ex.Message;
}
}
Related
In my application I have a map for which the first thing I do (on launching) is to add a custom MapLayer (which I populate with many MapOverlays/pushpins).
When I browse to another page of the app and then return to the map page, everything (ie the MapLayer that was drawn on my map) is gone.
It takes time to add it all over again each time the user navigates to the map page so I would like it to be fixed, drawn/added just once.
Any suggestions?
edit, added the code [I removed some details, the structure remains the same]:
private async void drawStations()
{
SQLiteAsyncConnection conn = new SQLiteAsyncConnection("stasy.sqlite");
List<line1_stations> lines = await conn.QueryAsync<line1_stations>("select *...");
Microsoft.Phone.Maps.Controls.MapLayer layer = new Microsoft.Phone.Maps.Controls.MapLayer();
Pushpin p;
foreach (line1_stations a in lines)
{
double sLat = Convert.ToDouble(a.lat);
double sLon = Convert.ToDouble(a.lon);
p = new Pushpin();
p.Location = new GeoCoordinate(sLat, sLon);
p.Tap += img_Tap;
p.Content = "...";
p.Foreground = new SolidColorBrush(Colors.Transparent);
p.Width = 30;
p.Height = 30;
MapOverlay overlay1 = new MapOverlay();
overlay1.Content = p;
overlay1.GeoCoordinate = new GeoCoordinate(sLat, sLon);
overlay1.PositionOrigin = new Point(0.0, 1.0);
layer.Add(overlay1);
}
myMap.Layers.Add(layer);
}
You can try to create your MapLayer as a public property in App.xaml.cs and set it only when your app is running first time.
Then create an instance of app inside page with your map and add your MapLayer to your Map layers inside OnNavigatedTo event.
Define a flag in app level. here is the sample
// In App.xaml.cs
public static bool IsLaunched = false;
private void Application_Launching(object sender, LaunchingEventArgs e)
{
IsLaunched =true;
}
//In your map screen
protected override void OnNavigatedTo(NavigationEventArgs e)
{
if(App.IsLaunched)
{
drawStations();
//Set App flage to false
App.IsLaunched = false;
}
}
private async void drawStations()
{
SQLiteAsyncConnection conn = new SQLiteAsyncConnection("stasy.sqlite");
List<line1_stations> lines = await conn.QueryAsync<line1_stations>("select *...");
Microsoft.Phone.Maps.Controls.MapLayer layer = new Microsoft.Phone.Maps.Controls.MapLayer();
Pushpin p;
foreach (line1_stations a in lines)
{
double sLat = Convert.ToDouble(a.lat);
double sLon = Convert.ToDouble(a.lon);
p = new Pushpin();
p.Location = new GeoCoordinate(sLat, sLon);
p.Tap += img_Tap;
p.Content = "...";
p.Foreground = new SolidColorBrush(Colors.Transparent);
p.Width = 30;
p.Height = 30;
MapOverlay overlay1 = new MapOverlay();
overlay1.Content = p;
overlay1.GeoCoordinate = new GeoCoordinate(sLat, sLon);
overlay1.PositionOrigin = new Point(0.0, 1.0);
layer.Add(overlay1);
}
myMap.Layers.Add(layer);
}
I want to update my live tile by creating and saving a writable bitmap image in scheduled task agent.my code works inside the app but in background task, it breaks into the debugger
I'm using this simple code:
protected override void OnInvoke(ScheduledTask task)
{
#if DEBUG_AGENT
ScheduledActionService.LaunchForTest(task.Name, TimeSpan.FromSeconds(30));
#endif
CreateWideTile();
NotifyComplete();
}
and my code to create and save image is this:
private void CreateWideTile()
{
int width = 691;
int height = 336;
string imagename = "WideBackground";
WriteableBitmap b = new WriteableBitmap(width, height);
var canvas = new Grid();
canvas.Width = b.PixelWidth;
canvas.Height = b.PixelHeight;
var background = new Canvas();
background.Height = b.PixelHeight;
background.Width = b.PixelWidth;
//Created background color as Accent color
SolidColorBrush backColor = new SolidColorBrush(Colors.Red);
background.Background = backColor;
var textBlock = new TextBlock();
textBlock.Text = "Example text";
textBlock.FontWeight = FontWeights.Normal;
textBlock.TextAlignment = TextAlignment.Left;
textBlock.Margin = new Thickness(20, 20, 0, 0);
textBlock.TextWrapping = TextWrapping.Wrap;
textBlock.Foreground = new SolidColorBrush(Colors.White); //color of the text on the Tile
textBlock.FontSize = 30;
canvas.Children.Add(textBlock);
b.Render(background, null);
b.Render(canvas, null);
b.Invalidate(); //Draw bitmap
//Save bitmap as jpeg file in Isolated Storage
using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream imageStream = new IsolatedStorageFileStream("/Shared/ShellContent/" + imagename + ".jpg", System.IO.FileMode.Create, isf))
{
b.SaveJpeg(imageStream, b.PixelWidth, b.PixelHeight, 0, 100);
}
}
}
when I test the app, after executing background task, an error comes that point to Debugger.Break();
private static void UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
{
if (Debugger.IsAttached)
{
// An unhandled exception has occurred; break into the debugger
Debugger.Break();
}
}
I don't understand the reason. my code works in foreground app but not in background ...
any solution ????
You should use dispatcher, because WriteableBitmap.Render should be used in the UI thread:
protected override void OnInvoke(ScheduledTask task)
{
Deployment.Current.Dispatcher.BeginInvoke( () =>
{
CreateWideTile();
NotifyComplete();
} );
}
I want to random a number of my array. Then I show it in a textblock. I want to do it every second. How to update my textblock every second ?. Please to help me.
Create a dispatcher timer and for every ticks update your textbock.
number = 0
dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
dispatcherTimer.Interval = new TimeSpan(0,0,1);
dispatcherTimer.Start();
private void dispatcherTimer_Tick(object sender, EventArgs e)
{
//if you use binding and mvvm
this.Text = number.tostring();
//if you don't use binding
yourTextblock.Text = number.toString();
number ++;
}
create dispatcher timer and every half second update text box
int number=0;
private DispatcherTimer _timer;
public sample()
{
InitializeComponent();
_timer = new DispatcherTimer();
_timer.Interval = new TimeSpan(0, 0, 0,0,500);
_timer.Tick += _timer_Tick;
_timer.Start();
}
void _timer_Tick(object sender, EventArgs e)
{
number++;
yourTextblock.Text = number.toString();
}
I'm using ink presenter to draw the strokes. But the problem is while drawing curved lines, its draws jagged lines.. Straight lines do not have a problem. This is how I have done.. I dont know where to make changes so as to make the lines smoother.
private void MyIP_MouseLeftButtonDown(object sender, MouseEventArgs e)
{
MyIP.CaptureMouse();
DrawingAttributes att = new DrawingAttributes();
att.Color = CB;
att.Width = StrokeWidth;
att.Height = StrokeWidth;
if (bErase == true)
{
StylusPointCollection ErasePointCollection = new StylusPointCollection();
ErasePointCollection.Add(e.StylusDevice.GetStylusPoints(MyIP));
lastPoint = ErasePointCollection[ErasePointCollection.Count - 1];
EraseStroke = new Stroke(ErasePointCollection);
EraseStroke.DrawingAttributes = att;
}
else
{
StylusPointCollection MyStylusPointCollection = new StylusPointCollection();
MyStylusPointCollection.Add(e.StylusDevice.GetStylusPoints(MyIP));
NewStroke = new Stroke(MyStylusPointCollection);
NewStroke.DrawingAttributes = att;
MyIP.Strokes.Add(NewStroke);
}
}
//StylusPoint objects are collected from the MouseEventArgs and added to MyStroke.
private void MyIP_MouseMove(object sender, MouseEventArgs e)
{
if (bErase == true)
{
//StylusPointCollection pointErasePoints = e.StylusDevice.GetStylusPoints(MyIP);
//EraseStroke.StylusPoints.Add(e.StylusDevice.GetStylusPoints(MyIP));
//pointErasePoints.Insert(0, lastPoint);
//StrokeCollection hitStrokes = MyIP.Strokes.HitTest(pointErasePoints);
//if (hitStrokes.Count > 0)
//{
// foreach (Stroke hitStroke in hitStrokes)
// {
// ////For each intersecting stroke, split the stroke into two while removing the intersecting points.
// ProcessPointErase(hitStroke, pointErasePoints);
// }
//}
//lastPoint = pointErasePoints[pointErasePoints.Count - 1];
//STROKEERASE METHOD
StylusPointCollection pointErasePoints = e.StylusDevice.GetStylusPoints(MyIP);
StrokeCollection hitStrokes = MyIP.Strokes.HitTest(pointErasePoints);
if (hitStrokes.Count > 0)
{
foreach (Stroke hitStroke in hitStrokes)
{
MyIP.Strokes.Remove(hitStroke);
undoStack.Push(hitStroke);
undoStateBufferStack.Push(true);
}
}
}
if (NewStroke != null)
NewStroke.StylusPoints.Add(e.StylusDevice.GetStylusPoints(MyIP));
}
//MyStroke is completed
private void MyIP_LostMouseCapture(object sender, MouseEventArgs e)
{
if (NewStroke != null)
{
undoStack.Push(NewStroke);
undoStateBufferStack.Push(false);
}
EraseStroke = null;
NewStroke = null;
}
//Set the Clip property of the inkpresenter so that the strokes
//are contained within the boundary of the inkpresenter
private void SetBoundary()
{
RectangleGeometry MyRectangleGeometry = new RectangleGeometry();
MyRectangleGeometry.Rect = new Rect(0, 0, MyIP.ActualWidth, MyIP.ActualHeight);
MyIP.Clip = MyRectangleGeometry;
}
You can find the sample source code describing ink presenter in this Download link
. Please find the download tag. Also it contains plenty other samples which helps you to learn windows phone deeper.
I'm develop a game with starling-framework.my problem is how to detect all tween is complete when I add a set of elements into juggler.
current my plan is
while(some_condition){ //allocate a set of tween
var tween=createTween(tweenCount++);
tween.onComplete=function(){
tweenCount--;
}
}
function checkComplete(){
if(tweenCount==0)
doStuff();
else
setTimeout(checkComplete,1000);
}
and there is any better solution ? thanks for your time!
update
write a simple class to solve this ,seems like better
public class TweenMonitor
{
public function TweenMonitor()
{
throw new Error('static class');
}
private static var refDict:Dictionary = new Dictionary();
public static function monit(tweens:Vector.<Tween>,onAllFinish:Function,id:String='$default$'):void
{
for (var i:int = 0; i < tweens.length; i++)
{
var tween:Tween = tweens[i];
if (tween == null)
continue;
if (refDict[id] == null) {
refDict[id] = 1;
}else
refDict[id]++;
tween.addEventListener(Event.REMOVE_FROM_JUGGLER,function (e:Event):void
{
refDict[id]--;
if (refDict[id] == 0)
onAllFinish && onAllFinish();
});
}
}
}
You simply need the onComplete property of Tween Class (Starling Framework)
Here is an Example :
function addTween() {
var tween:Tween = new Tween(object, 2.0, Transitions.EASE_IN_OUT);
tween.animate("x", object.x + 50);
tween.animate("rotation", deg2rad(45));
tween.fadeTo(0);
tween.onComplete = tween_complete;
Starling.juggler.add(tween);
}
function tween_complete() {
// Handle Tween Complete Action Here
}
EDIT
In case of multiple tweens, you probably could do better by attaching a timer class instead of settimeout:
while(some_condition){ //allocate a set of tween
var tween=createTween(tweenCount++);
tween.onComplete = function() { tweenCount--; }
}
var timer : Timer = new Timer(1000);
timer.addEventListener(TimerEvent.TIMER,update);
timer.start();
function update(e) {
if(tweenCount > 0) return;
timer.stop();
timer = null;
doStuff();
}
I would have done like this:
OnComplete = tweenDone;
...
function tweenDone() {
TweenCount--;
If(TweenCount == 0) doStuff();
}
Wrote this on a cell phone so I had to take a lot of shortcuts, if you need more info, leave a comment!