prevent zoom out on map page with navigation bar - c#

I want to stretch my map on a click of a toolbar button.
I succeed in that simply to go to another page (MapFullPage).
The problem is when I want on override BackButtonPressed through App.Current.Main = new MainMasterDetailPage(new MapPage()) it throwes me back, but my zoom isn't more desired zoom (when I leaved this page and went on MapFullPage), the zoom is small (I can see continents).
If I call App.Current.Main = new MapPage() it shows me the correct zoom.
Here is my two classes:
MapPage ->
public class MapPage : ContentPageCustom
{
//TKCustomMap mapView;
//TKCustomMapPin pinSelected;
DealerLocationResponseModel responseLocations;
DealerLocationResponseModel responseShops;
DealerLocationResponseModel responseStats;
DealerLocationResponseModel responseMoney;
public MapPage()
{
try
{
if (IsBusy)
return;
IsBusy = true;
this.CreateView();
}
catch (Exception ex)
{
DisplayAlert("Error", Constants.StandardError, "OK");
}
finally
{
IsBusy = false;
}
}
private async void CreateView()
{
try
{
Icon = "map-alt.png";
Title = "Locations";
var mapView = new TKCustomMap();
mapView.IsShowingUser = true;
mapView.SetBinding(TKCustomMap.CustomPinsProperty, "Pins");
mapView.SetBinding(TKCustomMap.MapClickedCommandProperty, "MapClickedCommand");
mapView.SetBinding(TKCustomMap.MapLongPressCommandProperty, "MapLongPressCommand");
mapView.SetBinding(TKCustomMap.MapCenterProperty, "MapCenter");
mapView.SetBinding(TKCustomMap.PinSelectedCommandProperty, "PinSelectedCommand");
mapView.SetBinding(TKCustomMap.SelectedPinProperty, "SelectedPin");
mapView.SetBinding(TKCustomMap.RoutesProperty, "Routes");
mapView.SetBinding(TKCustomMap.PinDragEndCommandProperty, "DragEndCommand");
mapView.SetBinding(TKCustomMap.CirclesProperty, "Circles");
mapView.SetBinding(TKCustomMap.CalloutClickedCommandProperty, "CalloutClickedCommand");
mapView.SetBinding(TKCustomMap.PolylinesProperty, "Lines");
mapView.SetBinding(TKCustomMap.PolygonsProperty, "Polygons");
mapView.SetBinding(TKCustomMap.MapRegionProperty, "MapRegion");
mapView.SetBinding(TKCustomMap.RouteClickedCommandProperty, "RouteClickedCommand");
mapView.SetBinding(TKCustomMap.RouteCalculationFinishedCommandProperty, "RouteCalculationFinishedCommand");
mapView.SetBinding(TKCustomMap.TilesUrlOptionsProperty, "TilesUrlOptions");
mapView.SetBinding(TKCustomMap.MapFunctionsProperty, "MapFunctions");
mapView.IsRegionChangeAnimated = true;
NavigationPage.SetHasBackButton(this, false);
BackgroundColor = Color.White;
responseLocations = ServiceProvider.GetDealerLocationServiceMethod(new DealerLocationRequestModel { MobilePhoneNumber = "063333333", UserIdentificator = "1234" });
if (!responseLocations.Succeeded)
{
await DisplayAlert("Greska", "Nije nadjena nijedna lokacija", "OK");
App.Current.MainPage = new HomeMasterDetail();
return;
}
List<TKCustomMapPin> pinLists = new List<TKCustomMapPin>();
foreach (var item in responseLocations.Dealers)
{
pinLists.Add(
new TKCustomMapPin
{
Image = "_mapPin_36x36",
IsCalloutClickable = true,
ShowCallout = true,
Position = new Position(item.Latitude, item.Longitude),
Title = item.LocationName + " " + item.Address,
Subtitle = item.LocationDescription
}
);
}
mapView.CustomPins = pinLists;
#region Stack and Buttons
mapView = new TKCustomMap(MapSpan.FromCenterAndRadius(mapView.CustomPins.ElementAt(1).Position, Distance.FromKilometers(2)));
mapView.CustomPins = new List<TKCustomMapPin>(pinLists);
mapView.IsShowingUser = true;
StackLayout btnCart = ElementsHelper.createImageButton("_cart_512x512.png", "Shops");
StackLayout btnStats = ElementsHelper.createImageButton("_stats_512x512.png", "Top up");
StackLayout btnMoney = ElementsHelper.createImageButton("_money_512x512.png", "Cash out");
StackLayout layout = new StackLayout
{
Orientation = StackOrientation.Horizontal,
HorizontalOptions = LayoutOptions.Center,
Children =
{
btnStats,
btnMoney,
btnCart
}
};
BoxView box1 = new BoxView { BackgroundColor = Color.Transparent, HeightRequest = Device.GetNamedSize(NamedSize.Large, typeof(Image)) * 2.5, WidthRequest = Device.GetNamedSize(NamedSize.Large, typeof(Image)) * 2.5 };
BoxView box2 = new BoxView { BackgroundColor = Color.Transparent, HeightRequest = Device.GetNamedSize(NamedSize.Large, typeof(Image)) * 2.5, WidthRequest = Device.GetNamedSize(NamedSize.Large, typeof(Image)) * 2.5 };
ActivityIndicator activityIndicator = new ActivityIndicator();
activityIndicator.Color = Constants.iPink;
activityIndicator.BindingContext = this;
activityIndicator.IsRunning = true;
activityIndicator.HeightRequest = 70;
activityIndicator.Margin = new Thickness(15, 0);
activityIndicator.SetBinding(ActivityIndicator.IsRunningProperty, "IsBusy");
activityIndicator.SetBinding(ActivityIndicator.IsVisibleProperty, "IsBusy");
layout.Children.Add(activityIndicator);
StackLayout layoutIndicator = new StackLayout { Orientation = StackOrientation.Horizontal };
layoutIndicator.Children.Add(box1);
layoutIndicator.Children.Add(activityIndicator);
layoutIndicator.Children.Add(box2);
layoutIndicator.IsVisible = false;
TapGestureRecognizer btnShopRecognizer = new TapGestureRecognizer();
btnShopRecognizer.Tapped += async (sender, e) =>
{
if (IsBusy)
return;
IsBusy = true;
layout.IsVisible = false;
layoutIndicator.IsVisible = true;
await Task.Delay(400);
responseShops = ServiceProvider.GetDealerLocationServiceMethod(new DealerLocationRequestModel { MobilePhoneNumber = "063333333", UserIdentificator = "1234" }, 1);
SetPins(mapView, responseShops);
mapView.MoveToRegion(MapSpan.FromCenterAndRadius(new Position(responseShops.Dealers.ElementAt(1).Latitude, responseShops.Dealers.ElementAt(1).Longitude), Distance.FromKilometers(2)));
SetActiveButtonMap(btnCart, btnStats, btnMoney);
IsBusy = false;
layoutIndicator.IsVisible = false;
layout.IsVisible = true;
};
TapGestureRecognizer btnMoneyRecognizer = new TapGestureRecognizer();
btnMoneyRecognizer.Tapped += async (sender, e) =>
{
if (IsBusy)
return;
IsBusy = true;
layout.IsVisible = false;
layoutIndicator.IsVisible = true;
await Task.Delay(400);
responseMoney = ServiceProvider.GetDealerLocationServiceMethod(new DealerLocationRequestModel { MobilePhoneNumber = "063333333", UserIdentificator = "1234" }, 2);
SetPins(mapView, responseMoney);
mapView.MoveToRegion(MapSpan.FromCenterAndRadius(new Position(responseMoney.Dealers.ElementAt(1).Latitude, responseMoney.Dealers.ElementAt(1).Longitude), Distance.FromKilometers(2)));
SetActiveButtonMap(btnMoney, btnStats, btnCart);
IsBusy = false;
layoutIndicator.IsVisible = false;
layout.IsVisible = true;
};
TapGestureRecognizer btnStatsRecognizer = new TapGestureRecognizer();
btnStatsRecognizer.Tapped += async (sender, e) =>
{
if (IsBusy)
return;
IsBusy = true;
layout.IsVisible = false;
layoutIndicator.IsVisible = true;
await Task.Delay(400);
responseStats = ServiceProvider.GetDealerLocationServiceMethod(new DealerLocationRequestModel { MobilePhoneNumber = "063333333", UserIdentificator = "1234" }, 3);
SetPins(mapView, responseStats);
mapView.MoveToRegion(MapSpan.FromCenterAndRadius(new Position(responseStats.Dealers.ElementAt(1).Latitude, responseStats.Dealers.ElementAt(1).Longitude), Distance.FromKilometers(2)));
SetActiveButtonMap(btnStats, btnMoney, btnCart);
IsBusy = false;
layoutIndicator.IsVisible = false;
layout.IsVisible = true;
};
btnCart.GestureRecognizers.Add(btnShopRecognizer);
btnMoney.GestureRecognizers.Add(btnMoneyRecognizer);
btnStats.GestureRecognizers.Add(btnStatsRecognizer);
#endregion
RelativeLayout _baseLayout = new RelativeLayout { VerticalOptions = LayoutOptions.FillAndExpand };
_baseLayout.Children.Add(
mapView,
Constraint.RelativeToParent((parent) =>
{
return (0);
}),
Constraint.RelativeToParent((parent) =>
{
return (0);
}),
heightConstraint: Constraint.RelativeToParent((r) => r.Height),
widthConstraint: Constraint.RelativeToParent((r) => r.Width));
Func<RelativeLayout, double> getLayoutWidth = (p) => layout.Measure(_baseLayout.Width, _baseLayout.Height).Request.Width;
_baseLayout.Children.Add(layout,
Constraint.RelativeToParent((parent) => parent.Width / 2 - getLayoutWidth(parent) / 2),
Constraint.RelativeToParent((parent) =>
{
return (.8 * parent.Height);
})
);
_baseLayout.Children.Add(layoutIndicator,
Constraint.RelativeToParent((parent) => parent.Width / 2 - getLayoutWidth(parent) / 2),
Constraint.RelativeToParent((parent) =>
{
return (.8 * parent.Height);
})
);
//_baseLayout.Children.Add(activityIndicator,
//Constraint.RelativeToParent((parent) => parent.Width / 2),
//Constraint.RelativeToParent((parent) =>
//{
// return (.8 * parent.Height);
//})
//);
Constraint.RelativeToParent((parent) =>
{
return (1);
});
_baseLayout.HeightRequest = App.ScreenHeight - 200;
Content = _baseLayout;
}
catch
{
await DisplayAlert("Error", Constants.StandardError, "OK");
}
//this._baseLayout.Children.Add(
// mapView,
// Constraint.RelativeToView(autoComplete, (r, v) => v.X),
// Constraint.RelativeToView(autoComplete, (r, v) => autoComplete.HeightOfSearchBar),
// heightConstraint: Constraint.RelativeToParent((r) => r.Height - autoComplete.HeightOfSearchBar),
// widthConstraint: Constraint.RelativeToView(autoComplete, (r, v) => v.Width));
//this._baseLayout.Children.Add(
// autoComplete,
// Constraint.Constant(0),
// Constraint.Constant(0));
}
private void SetPins(TKCustomMap map, DealerLocationResponseModel dealerModel = null)
{
List<TKCustomMapPin> pinLists = new List<TKCustomMapPin>();
foreach (var item in dealerModel.Dealers)
{
pinLists.Add(
new TKCustomMapPin
{
Image = "_mapPin_36x36",
IsCalloutClickable = true,
ShowCallout = true,
Position = new Position(item.Latitude, item.Longitude),
Title = item.LocationName + " " + item.Address,
Subtitle = item.LocationDescription,
}
);
}
//map.CustomPins = null;
map.CustomPins = pinLists;
}
private void SetActiveButtonMap(StackLayout activeImage, StackLayout disabledImage1, StackLayout disabledImage2)
{
var a = ((activeImage.Children[0] as Image).Source as FileImageSource).File;
if ((!((activeImage.Children[0] as Image).Source as FileImageSource).File.ToString().Contains("_active")))
//Set active image
StartClickCustom(activeImage.Children[0] as Image);
//Remove active images
if (((disabledImage1.Children[0] as Image).Source as FileImageSource).File.ToString().Contains("_active"))
{
EndClickCustom(disabledImage1.Children[0] as Image);
}
if (((disabledImage2.Children[0] as Image).Source as FileImageSource).File.ToString().Contains("_active"))
{
EndClickCustom(disabledImage2.Children[0] as Image);
}
}
}
and MapFullPage is the same (copy/pasted) just has onBack method:
protected override bool OnBackButtonPressed()
{
App.fromBack = true;
App.Current.MainPage = new MainMasterDetailPage(new MapPage());
return true;
}

Related

Device.BeginInvokeOnThread() block the await operator.Is there any other way to update the UI in xamarin forms

I am working on xamarin forms Cross platform.
I have a function createform in which i am calling the buildform function.My build form function is used to generate the UI.
I am callling my create form inside the constructor.
public FormsPage()
{
json = new JsonSerialize();
//Task.createForm("form5");
Task.Run(() => createForm("form5")).Wait();
}
public async void createForm(string path)
{
this.path = path;
definition =json.parseJson(path);
formdata = await json.parseJsonFormData(path);
//var x = (bool)formdata["Form"][1]["Section_OtherInfo"]["IsNop"];
// buildForm();
Device.BeginInvokeOnMainThread(buildForm);
}
If i am not using Device.BeginInvokeOnMainThread(buildForm) then it is throwing an exception for UWP.And If i am using Device.BeginInvokeOnMainThread(buildForm) then it is blocking the await operator.
The prototype of my BUildForm function is:
public void buildForm()
{
try
{
JToken y = formdata["Form"];
if (!(y.HasValues))
{
CreateJson();
}
data.Clear();
var section = new StackLayout
{
BackgroundColor = Color.White,
HorizontalOptions = LayoutOptions.FillAndExpand
};
var sectionLayout = new StackLayout
{
Padding = 10,
BackgroundColor = Color.White,
HorizontalOptions = LayoutOptions.FillAndExpand
};
var sectionheader = new StackLayout
{
BackgroundColor = Color.FromHex("#7635EB"),
HorizontalOptions = LayoutOptions.FillAndExpand
};
var mainLayout = new StackLayout
{
Padding = 10,
BackgroundColor = Color.FromHex("#DCDCDC")
};
var horizontalLayoutNaNop = new StackLayout
{
Orientation = StackOrientation.Horizontal,
BackgroundColor = Color.White
};
var horizontalLayout = new StackLayout
{
Orientation = StackOrientation.Horizontal,
BackgroundColor = Color.White
};
this.Title = definition.Title;
//foreach (var sc in definition.Section)
for (var i = 0; i < definition.Section.Count; i++)
{
section = new StackLayout
{
BackgroundColor = Color.White,
HorizontalOptions = LayoutOptions.FillAndExpand
};
sectionheader = new StackLayout
{
BackgroundColor = Color.FromHex("#7635EB"),
HorizontalOptions = LayoutOptions.FillAndExpand
};
horizontalLayout = new StackLayout
{
Orientation = StackOrientation.Horizontal,
BackgroundColor = Color.White
};
sectionLayout = new StackLayout
{
Padding = 10,
BackgroundColor = Color.White,
HorizontalOptions = LayoutOptions.FillAndExpand
};
if (definition.Section[i].SectionTitle != string.Empty)
{
var title = new Label
{
Text = definition.Section[i].SectionTitle,
HorizontalTextAlignment = TextAlignment.Start,
TextColor = Color.White,
FontSize = 20,
FontAttributes = FontAttributes.Bold,
Margin = new Thickness(10, 5, 5, 5)
};
sectionheader.Children.Add(title);
section.Children.Add(sectionheader);
}
if (definition.Section[i].IsNa || definition.Section[i].IsNop)
{
horizontalLayoutNaNop = new StackLayout
{
Orientation = StackOrientation.Horizontal,
BackgroundColor = Color.White
};
if (definition.Section[i].IsNa)
{
if ((string)formdata["Form"][i][definition.Section[i].SectionId]["IsNa"] == string.Empty)
{
formdata["Form"][i][definition.Section[i].SectionId]["IsNa"] = false;
}
var Na = new KanCheckBox("NA");
Na.StyleId = "IsNa";
Na.IsChecked = (bool)formdata["Form"][i][definition.Section[i].SectionId]["IsNa"];
data.Add("IsNa", (string)formdata["Form"][i][definition.Section[i].SectionId]["IsNa"]);
Na.OnCheckedChange += (object s, bool IsChecked) =>
{
data[Na.StyleId] = Convert.ToString(IsChecked);
};
horizontalLayoutNaNop.Children.Add(Na);
}
if (definition.Section[i].IsNop)
{
if ((string)formdata["Form"][i][definition.Section[i].SectionId]["IsNop"] == string.Empty)
{
formdata["Form"][i][definition.Section[i].SectionId]["IsNop"] = false;
}
var Nop = new KanCheckBox("No Problem Found");
Nop.StyleId = "IsNop";
Nop.IsChecked = (bool)formdata["Form"][i][definition.Section[i].SectionId]["IsNop"];
data.Add("IsNop", (string)formdata["Form"][i][definition.Section[i].SectionId]["IsNop"]);
Nop.OnCheckedChange += (object s, bool IsChecked) =>
{
data[Nop.StyleId] = Convert.ToString(IsChecked);
};
horizontalLayoutNaNop.Children.Add(Nop);
}
sectionLayout.Children.Add(horizontalLayoutNaNop);
sectionLayout.Children.Add(new BoxView
{
BackgroundColor = Color.FromHex("#ECECEC"),
HeightRequest = 1,
HorizontalOptions = LayoutOptions.FillAndExpand
});
}
if (definition.Section[i].subsection.Count != 0)
{
foreach (var sub in definition.Section[i].subsection)
{
if (sub.SubSectionTitle != string.Empty)
{
var subtitle = new Label
{
Text = sub.SubSectionTitle,
HorizontalTextAlignment = TextAlignment.Start,
FontSize = 15,
FontAttributes = FontAttributes.Bold,
TextColor = Color.FromHex("#7635EB")
};
sectionLayout.Children.Add(subtitle);
}
// (string)formdata["Form"][i][definition.Section[i].SectionId][el.Property]
foreach (var el in sub.elements)
{
var x = el.Type;
//AddElements(el, true, i, definition.Section[i].SectionId, sectionLayout, horizontalLayout);
int lvl = 0;
Dictionary<string, List<FormElement>> dt = new Dictionary<string, List<FormElement>>();
List<FormElement> lt = new List<FormElement>();
Stack<FormElement> stk = new Stack<FormElement>();
stk.Push(el);
while (stk.Count > 0)
{
var parent = stk.Pop();
if (parent.Elements.Count != 0)
{
AddElements(parent, true, i, definition.Section[i].SectionId, sectionLayout, horizontalLayout);
while (stk.Count != 0)
{
lt.Add(stk.Pop());
}
if (lt.Count != 0)
{
dt.Add("child" + lvl, lt);
lt = new List<FormElement>();
lvl++;
}
for (var j = 1; j <= parent.Elements.Count; j++)
{
stk.Push(parent.Elements[parent.Elements.Count - j]);
}
}
else
{
if (stk.Count > 0)
{
AddElements(parent, false, i, definition.Section[i].SectionId, sectionLayout, horizontalLayout);
}
else
{
AddElements(parent, false, i, definition.Section[i].SectionId, sectionLayout, horizontalLayout);
if (dt.Count > 0)
{
lt = dt["child" + lvl];
dt.Remove("child" + lvl);
for (var j = 1; j <= lt.Count; j++)
{
stk.Push(lt[lt.Count - j]);
lvl--;
}
}
}
}
}
if (horizontalLayout.Children.Count != 0)
{
sectionLayout.Children.Add(horizontalLayout);
horizontalLayout = new StackLayout
{
Orientation = StackOrientation.Horizontal,
BackgroundColor = Color.White
};
}
}
}
}
section.Children.Add(sectionLayout);
mainLayout.Children.Add(section);
}
this.Content = new ScrollView
{
Content = mainLayout
};
}
catch(Exception ex)
{
}
}
Here i am trying to generate the form dynamically using BuildForm.
For the first time it is generating the ui without any problem.
And when the createform is called again then the await operator is blocked.
Is there any way to get to know that MainThread has stopped executing?
Or Any way to create the child thread as a main thread so that my await operator works.
I think you are a little confused with the concepts here. My Spidey Senses tells me the deadlock is because of an Unhandled Exception regardless of the UI
The first thing is the async void looks suspicious, secondly i think there is an Exception happening somewhere regardless (and you need to figure that out)
private void Start()
{
// invoke
Device.BeginInvokeOnMainThread(SomeMethod);
}
private async void SomeMethod()
{
try
{
// await method
await SomeAsyncMethod();
}
catch (Exception e) // handle whatever exceptions you expect
{
//Handle exceptions
}
}
private async Task SomeAsyncMethod()
{
// in this case lets push a new page
await Navigation.PushModalAsync(new ContentPage());
}
Although this is an example the take home here is, if there is a chance of not being on the UI thread, dispatch it on the main thread and if you are going down the road of fire-and-forget (suspicious) make sure you are handling your exceptions
Have you tryed calling the method asynchronoulsy?
private async Task ConectarWSAsync()
{
Device.BeginInvokeOnMainThread(
async () =>
{
lblStatus.Text = "Getting token WS...";
await ws.ConnectAsync();
lblStatus.Text = "WS connected";
}
);
}

Custom MessageBox with custom-defined Buttons [duplicate]

I am doing C# application, and I want to change the style of a message box. Is it possible or not?
Example: change button style, fore color, etc.
You can't restyle the default MessageBox as that's dependant on the current Windows OS theme, however you can easily create your own MessageBox. Just add a new form (i.e. MyNewMessageBox) to your project with these settings:
FormBorderStyle FixedToolWindow
ShowInTaskBar False
StartPosition CenterScreen
To show it use myNewMessageBoxInstance.ShowDialog();. And add a label and buttons to your form, such as OK and Cancel and set their DialogResults appropriately, i.e. add a button to MyNewMessageBox and call it btnOK. Set the DialogResult property in the property window to DialogResult.OK. When that button is pressed it would return the OK result:
MyNewMessageBox myNewMessageBoxInstance = new MyNewMessageBox();
DialogResult result = myNewMessageBoxInstance.ShowDialog();
if (result == DialogResult.OK)
{
// etc
}
It would be advisable to add your own Show method that takes the text and other options you require:
public DialogResult Show(string text, Color foreColour)
{
lblText.Text = text;
lblText.ForeColor = foreColour;
return this.ShowDialog();
}
MessageBox::Show uses function from user32.dll, and its style is dependent on Windows, so you cannot change it like that, you have to create your own form
Here is the code needed to create your own message box:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace MyStuff
{
public class MyLabel : Label
{
public static Label Set(string Text = "", Font Font = null, Color ForeColor = new Color(), Color BackColor = new Color())
{
Label l = new Label();
l.Text = Text;
l.Font = (Font == null) ? new Font("Calibri", 12) : Font;
l.ForeColor = (ForeColor == new Color()) ? Color.Black : ForeColor;
l.BackColor = (BackColor == new Color()) ? SystemColors.Control : BackColor;
l.AutoSize = true;
return l;
}
}
public class MyButton : Button
{
public static Button Set(string Text = "", int Width = 102, int Height = 30, Font Font = null, Color ForeColor = new Color(), Color BackColor = new Color())
{
Button b = new Button();
b.Text = Text;
b.Width = Width;
b.Height = Height;
b.Font = (Font == null) ? new Font("Calibri", 12) : Font;
b.ForeColor = (ForeColor == new Color()) ? Color.Black : ForeColor;
b.BackColor = (BackColor == new Color()) ? SystemColors.Control : BackColor;
b.UseVisualStyleBackColor = (b.BackColor == SystemColors.Control);
return b;
}
}
public class MyImage : PictureBox
{
public static PictureBox Set(string ImagePath = null, int Width = 60, int Height = 60)
{
PictureBox i = new PictureBox();
if (ImagePath != null)
{
i.BackgroundImageLayout = ImageLayout.Zoom;
i.Location = new Point(9, 9);
i.Margin = new Padding(3, 3, 2, 3);
i.Size = new Size(Width, Height);
i.TabStop = false;
i.Visible = true;
i.BackgroundImage = Image.FromFile(ImagePath);
}
else
{
i.Visible = true;
i.Size = new Size(0, 0);
}
return i;
}
}
public partial class MyMessageBox : Form
{
private MyMessageBox()
{
this.panText = new FlowLayoutPanel();
this.panButtons = new FlowLayoutPanel();
this.SuspendLayout();
//
// panText
//
this.panText.Parent = this;
this.panText.AutoScroll = true;
this.panText.AutoSize = true;
this.panText.AutoSizeMode = AutoSizeMode.GrowAndShrink;
//this.panText.Location = new Point(90, 90);
this.panText.Margin = new Padding(0);
this.panText.MaximumSize = new Size(500, 300);
this.panText.MinimumSize = new Size(108, 50);
this.panText.Size = new Size(108, 50);
//
// panButtons
//
this.panButtons.AutoSize = true;
this.panButtons.AutoSizeMode = AutoSizeMode.GrowAndShrink;
this.panButtons.FlowDirection = FlowDirection.RightToLeft;
this.panButtons.Location = new Point(89, 89);
this.panButtons.Margin = new Padding(0);
this.panButtons.MaximumSize = new Size(580, 150);
this.panButtons.MinimumSize = new Size(108, 0);
this.panButtons.Size = new Size(108, 35);
//
// MyMessageBox
//
this.AutoScaleDimensions = new SizeF(8F, 19F);
this.AutoScaleMode = AutoScaleMode.Font;
this.ClientSize = new Size(206, 133);
this.Controls.Add(this.panButtons);
this.Controls.Add(this.panText);
this.Font = new Font("Calibri", 12F, FontStyle.Regular, GraphicsUnit.Point, ((byte)(0)));
this.FormBorderStyle = FormBorderStyle.FixedSingle;
this.Margin = new Padding(4);
this.MaximizeBox = false;
this.MinimizeBox = false;
this.MinimumSize = new Size(168, 132);
this.Name = "MyMessageBox";
this.ShowIcon = false;
this.ShowInTaskbar = false;
this.StartPosition = FormStartPosition.CenterScreen;
this.ResumeLayout(false);
this.PerformLayout();
}
public static string Show(Label Label, string Title = "", List<Button> Buttons = null, PictureBox Image = null)
{
List<Label> Labels = new List<Label>();
Labels.Add(Label);
return Show(Labels, Title, Buttons, Image);
}
public static string Show(string Label, string Title = "", List<Button> Buttons = null, PictureBox Image = null)
{
List<Label> Labels = new List<Label>();
Labels.Add(MyLabel.Set(Label));
return Show(Labels, Title, Buttons, Image);
}
public static string Show(List<Label> Labels = null, string Title = "", List<Button> Buttons = null, PictureBox Image = null)
{
if (Labels == null) Labels = new List<Label>();
if (Labels.Count == 0) Labels.Add(MyLabel.Set(""));
if (Buttons == null) Buttons = new List<Button>();
if (Buttons.Count == 0) Buttons.Add(MyButton.Set("OK"));
List<Button> buttons = new List<Button>(Buttons);
buttons.Reverse();
int ImageWidth = 0;
int ImageHeight = 0;
int LabelWidth = 0;
int LabelHeight = 0;
int ButtonWidth = 0;
int ButtonHeight = 0;
int TotalWidth = 0;
int TotalHeight = 0;
MyMessageBox mb = new MyMessageBox();
mb.Text = Title;
//Image
if (Image != null)
{
mb.Controls.Add(Image);
Image.MaximumSize = new Size(150, 300);
ImageWidth = Image.Width + Image.Margin.Horizontal;
ImageHeight = Image.Height + Image.Margin.Vertical;
}
//Labels
List<int> il = new List<int>();
mb.panText.Location = new Point(9 + ImageWidth, 9);
foreach (Label l in Labels)
{
mb.panText.Controls.Add(l);
l.Location = new Point(200, 50);
l.MaximumSize = new Size(480, 2000);
il.Add(l.Width);
}
int mw = Labels.Max(x => x.Width);
il.ToString();
Labels.ForEach(l => l.MinimumSize = new Size(Labels.Max(x => x.Width), 1));
mb.panText.Height = Labels.Sum(l => l.Height);
mb.panText.MinimumSize = new Size(Labels.Max(x => x.Width) + mb.ScrollBarWidth(Labels), ImageHeight);
mb.panText.MaximumSize = new Size(Labels.Max(x => x.Width) + mb.ScrollBarWidth(Labels), 300);
LabelWidth = mb.panText.Width;
LabelHeight = mb.panText.Height;
//Buttons
foreach (Button b in buttons)
{
mb.panButtons.Controls.Add(b);
b.Location = new Point(3, 3);
b.TabIndex = Buttons.FindIndex(i => i.Text == b.Text);
b.Click += new EventHandler(mb.Button_Click);
}
ButtonWidth = mb.panButtons.Width;
ButtonHeight = mb.panButtons.Height;
//Set Widths
if (ButtonWidth > ImageWidth + LabelWidth)
{
Labels.ForEach(l => l.MinimumSize = new Size(ButtonWidth - ImageWidth - mb.ScrollBarWidth(Labels), 1));
mb.panText.Height = Labels.Sum(l => l.Height);
mb.panText.MinimumSize = new Size(Labels.Max(x => x.Width) + mb.ScrollBarWidth(Labels), ImageHeight);
mb.panText.MaximumSize = new Size(Labels.Max(x => x.Width) + mb.ScrollBarWidth(Labels), 300);
LabelWidth = mb.panText.Width;
LabelHeight = mb.panText.Height;
}
TotalWidth = ImageWidth + LabelWidth;
//Set Height
TotalHeight = LabelHeight + ButtonHeight;
mb.panButtons.Location = new Point(TotalWidth - ButtonWidth + 9, mb.panText.Location.Y + mb.panText.Height);
mb.Size = new Size(TotalWidth + 25, TotalHeight + 47);
mb.ShowDialog();
return mb.Result;
}
private FlowLayoutPanel panText;
private FlowLayoutPanel panButtons;
private int ScrollBarWidth(List<Label> Labels)
{
return (Labels.Sum(l => l.Height) > 300) ? 23 : 6;
}
private void Button_Click(object sender, EventArgs e)
{
Result = ((Button)sender).Text;
Close();
}
private string Result = "";
}
}

How to return a value only when "ok" is clicked

I have created a custimazibale prompt
public static class Prompt
{
public static string ShowDialog(int columnnumber, string columnname)
{
Form prompt = new Form();
prompt.Width = 500;
prompt.Height = 150;
prompt.FormBorderStyle = FormBorderStyle.FixedDialog;
prompt.Text = columnname;
prompt.StartPosition = FormStartPosition.CenterScreen;
Label textLabel = new Label() { Left = 50, Top = 20 };
ComboBox comboBox = new ComboBox() { Left = 50, Top = 50, Width = 400 };
comboBox.Items.AddRange(new string[] { "a","b","c" });
comboBox.DropDownStyle = ComboBoxStyle.DropDownList;
comboBox.SelectedItem = columnname;
Button confirmation = new Button() { Text = "Ok", Left = 350, Width = 100, Top = 80 };
confirmation.Click += (sender, e) => { prompt.Close(); };
textLabel.Text = "Colonne " + (columnnumber + 1).ToString() + " : " + columnname;
prompt.Controls.Add(comboBox);
prompt.Controls.Add(confirmation);
prompt.Controls.Add(textLabel);
prompt.AcceptButton = confirmation;
prompt.ShowDialog();
prompt.AcceptButton = confirmation;
return comboBox.Text;
}
}
then I call it in my main form when a header is clicked
private void dataGridView1_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
dt.Columns[e.ColumnIndex].ColumnName = Prompt.ShowDialog(e.ColumnIndex, dataGridView1.Columns[e.ColumnIndex].Name);
}
The problem is my text change even if the button close is clicked.
But I want it to change only when the user click the button "OK".
You could evaluate the DialogResult and return null if it is not OK:
public static class Prompt
{
public static string ShowDialog(int columnnumber, string columnname)
{
using (Form prompt = new Form())
{
// other code
return prompt.DialogResult == DialogResult.OK ? comboBox.Text : null;
}
}
}
and then in your other method:
private void dataGridView1_ColumnHeaderMouseClick(object sender, EventArgs e)
{
var result = Prompt.ShowDialog(e.ColumnIndex,
dataGridView1.Columns[e.ColumnIndex].Name);
if (result != null)
dt.Columns[e.ColumnIndex].ColumnName = result;
}
And inside your prompt you should set the DialogResult accordingly:
confirmation.Click += (sender, e) =>
{
prompt.DialogResult = DialogResult.OK;
prompt.Close();
};
HINT: Instead of result != null you could also use !String.IsNullOrWhiteSpace(result) to only update the column name if something was entered.
I would go for something like this:
using(Form prompt = new Form())
{
//Initialize the components of your form
DialogResult result = prompt.ShowDialog();
if(result == DialogResult.OK)
{
//return whatever it is you want to return
}
}
Inside your form you can set the DialogResult via prompt.DialogResult = DialogResult.OK and some more options (DialogResult.Cancel, DialogResult.Retry etc.)
You can set a bool when it is confirmed, and use that to return null if it wasn't confirmed, like this:
public static string ShowDialog(int columnnumber, string columnname)
{
Form prompt = new Form();
prompt.Width = 500;
prompt.Height = 150;
prompt.FormBorderStyle = FormBorderStyle.FixedDialog;
prompt.Text = columnname;
prompt.StartPosition = FormStartPosition.CenterScreen;
Label textLabel = new Label()
{
Left = 50,
Top = 20
};
ComboBox comboBox = new ComboBox()
{
Left = 50,
Top = 50,
Width = 400
};
comboBox.Items.AddRange(new string[] { "a", "b", "c" });
comboBox.DropDownStyle = ComboBoxStyle.DropDownList;
comboBox.SelectedItem = columnname;
Button confirmation = new Button()
{
Text = "Ok",
Left = 350,
Width = 100,
Top = 80
};
bool confirmed = false;
confirmation.Click += (sender, e) =>
{
prompt.Close();
confirmed = true;
};
textLabel.Text = "Colonne " + (columnnumber + 1).ToString() + " : " + columnname;
prompt.Controls.Add(comboBox);
prompt.Controls.Add(confirmation);
prompt.Controls.Add(textLabel);
prompt.AcceptButton = confirmation;
prompt.ShowDialog();
prompt.AcceptButton = confirmation;
return confirmed ? comboBox.Text : null;
}
Your calling code will need to check the return value for null, and only do something if the returned value is not null.

monotouch NSMutableAttributedString AddAttribute

I'm trying to do a rich text editor toolbar with 4 basic buttons (bold, italic, underline + color), here what I've got actually:
public override UIView InputAccessoryView
{
get
{
UIToolbar toolbar = new UIToolbar(new RectangleF(0, 0, 320, 30));
var fixedSpace = new UIBarButtonItem(UIBarButtonSystemItem.FixedSpace, null)
{
Width = 26
};
var flexibleSpace = new UIBarButtonItem(UIBarButtonSystemItem.FlexibleSpace, null);
boldItem = new UIBarButtonItem("B", UIBarButtonItemStyle.Plain, (o, e) => { GoBold(); });
italicItem = new UIBarButtonItem("I", UIBarButtonItemStyle.Plain, (o, e) => { GoItalic(); });
underlineItem = new UIBarButtonItem("U", UIBarButtonItemStyle.Plain, (o, e) => { GoUnderlined(); });
redItem = new UIBarButtonItem("R", UIBarButtonItemStyle.Plain, (o, e) => { GoRed(); });
toolbar.Items = new UIBarButtonItem[] { underlineItem, fixedSpace, italicItem, flexibleSpace, boldItem, fixedSpace, redItem };
return toolbar;
}
}
protected NSRange GetTextRange()
{
return new NSRange(
textField.GetOffsetFromPosition(textField.BeginningOfDocument, textField.SelectedTextRange.start),
textField.GetOffsetFromPosition(textField.SelectedTextRange.start, textField.SelectedTextRange.end)
);
}
protected void GoItalic()
{
NSMutableAttributedString text = new NSMutableAttributedString(textField.AttributedText);
text.AddAttribute(CTStringAttributeKey.Font, UIFont.ItalicSystemFontOfSize(20f), GetTextRange());
textField.AttributedText = text;
}
protected void GoUnderlined()
{
NSMutableAttributedString text = new NSMutableAttributedString(textField.AttributedText);
text.AddAttribute(CTStringAttributeKey.UnderlineStyle, new NSNumber((int) NSUnderlineStyle.Single), GetTextRange());
//text.AddAttribute(CTStringAttributeKey.UnderlineStyle, new NSNumber(NSUnderlineStyle.Single as int), GetTextRange());
textField.AttributedText = text;
}
protected void GoBold()
{
NSMutableAttributedString text = new NSMutableAttributedString(textField.AttributedText);
text.AddAttribute(CTStringAttributeKey.Font, UIFont.BoldSystemFontOfSize(20f), GetTextRange());
textField.AttributedText = text;
}
protected void GoRed()
{
NSMutableAttributedString text = new NSMutableAttributedString(textField.AttributedText);
text.AddAttribute(CTStringAttributeKey.UnderlineColor, UIColor.Red, GetTextRange());
textField.AttributedText = text;
}
Bold and Italic works just fine, but no way of making Underline and color works :/, I've succeded in applying underline to my selection with a crappy cast but I'd rather know how it should be done.
Seems I'm facing a casting problem, since NSUnderlineStyle.Single returns an enum where an object is expected, same goes for colors

MediaElement freezes video

I apply some LinearGradientBrush animation to MediaElement and after this video is freezing.
I try to reset it via Player1.OpacityMask = null; but no joy.
By the way if I animate Opacity of the MediaElement then video shows good as usually.
Any clue what's up? How to fix the video freezing after applying LinearGradientBrush animation to MediaElement ?
Thank you!
/// <summary>
/// Interaction logic for WipeTransition.xaml
/// </summary>
public partial class WipeTransition
{
public WipeDirections Direction { set; get; }
public TimeSpan Duration = TimeSpan.FromSeconds(2);
public bool StopPrevPlayerOnAnimationStarts;
Random rdm = new Random(1);
bool isPlayer1;
public WipeTransition()
{
InitializeComponent();
try
{
Loaded += WipeTransition_Loaded;
SizeChanged += WipeTransition_SizeChanged;
Player1.CacheMode = new BitmapCache();
Player1.LoadedBehavior = MediaState.Manual;
Player2.CacheMode = new BitmapCache();
Player2.LoadedBehavior = MediaState.Manual;
Direction = WipeDirections.RandomDirection;
Player1.Width = ActualWidth;
Player2.Width = ActualWidth;
Player1.Height = ActualHeight;
Player2.Height = ActualHeight;
isPlayer1 = true;
}
catch (Exception)
{
}
}
void WipeTransition_SizeChanged(object sender, SizeChangedEventArgs e)
{
Player1.Width = ActualWidth;
Player2.Width = ActualWidth;
Player1.Height = ActualHeight;
Player2.Height = ActualHeight;
}
void WipeTransition_Loaded(object sender, RoutedEventArgs e)
{
Player1.Width = ActualWidth;
Player2.Width = ActualWidth;
Player1.Height = ActualHeight;
Player2.Height = ActualHeight;
}
public void Start(Uri uri)
{
try
{
Debug.WriteLine("************** START ANIMATION ***************************************");
Player1.Width = ActualWidth;
Player2.Width = ActualWidth;
Player1.Height = ActualHeight;
Player2.Height = ActualHeight;
// We start to Animate one of the Player is on BACK
if (isPlayer1)
{
if (StopPrevPlayerOnAnimationStarts)
Player2.Stop();
Canvas.SetZIndex(Player2, 49);
Canvas.SetZIndex(Player1, 50);
Player1.Source = uri;
Debug.WriteLine("Player1 - ANIMATE");
WipeAnimation(Player1);
}
else // Player2
{
if (StopPrevPlayerOnAnimationStarts)
Player1.Stop();
Canvas.SetZIndex(Player1, 49);
Canvas.SetZIndex(Player2, 50);
Player2.Source = uri;
Debug.WriteLine("Player2 - ANIMATE");
WipeAnimation(Player2);
}
}
catch (Exception)
{
}
}
public void WipeAnimation(FrameworkElement ObjectToAnimate)
{
try
{
LinearGradientBrush OpacityBrush = new LinearGradientBrush();
#region Setup Wipe Direction
switch (Direction)
{
case WipeDirections.RightToLeft:
OpacityBrush.StartPoint = new Point(1, 0);
OpacityBrush.EndPoint = new Point(0, 0);
break;
case WipeDirections.LeftToRight:
OpacityBrush.StartPoint = new Point(0, 0);
OpacityBrush.EndPoint = new Point(1, 0);
break;
case WipeDirections.BottomToTop:
OpacityBrush.StartPoint = new Point(0, 1);
OpacityBrush.EndPoint = new Point(0, 0);
break;
case WipeDirections.TopToBottom:
OpacityBrush.StartPoint = new Point(0, 0);
OpacityBrush.EndPoint = new Point(0, 1);
break;
case WipeDirections.RandomDirection:
#region
int randomValue = rdm.Next(0, 3);
if (randomValue == 0)
{
OpacityBrush.StartPoint = new Point(1, 0);
OpacityBrush.EndPoint = new Point(0, 0);
}
else if (randomValue == 1)
{
OpacityBrush.StartPoint = new Point(0, 0);
OpacityBrush.EndPoint = new Point(0, 1);
}
else if (randomValue == 2)
{
OpacityBrush.StartPoint = new Point(0, 0);
OpacityBrush.EndPoint = new Point(1, 0);
}
else if (randomValue == 3)
{
OpacityBrush.StartPoint = new Point(0, 1);
OpacityBrush.EndPoint = new Point(0, 0);
}
#endregion
break;
}
#endregion
GradientStop BlackStop = new GradientStop(Colors.Black, 0);
GradientStop TransparentStop = new GradientStop(Colors.Transparent, 0);
if (FindName("TransparentStop") != null)
UnregisterName("TransparentStop");
RegisterName("TransparentStop", TransparentStop);
if (FindName("BlackStop") != null)
UnregisterName("BlackStop");
this.RegisterName("BlackStop", BlackStop);
OpacityBrush.GradientStops.Add(BlackStop);
OpacityBrush.GradientStops.Add(TransparentStop);
ObjectToAnimate.OpacityMask = OpacityBrush;
Storyboard sb = new Storyboard();
DoubleAnimation DA = new DoubleAnimation() { From = 0, To = 1, Duration = Duration };
DoubleAnimation DA2 = new DoubleAnimation() { From = 0, To = 1, Duration = Duration };
sb.Children.Add(DA); sb.Children.Add(DA2);
Storyboard.SetTargetName(DA, "TransparentStop");
Storyboard.SetTargetName(DA2, "BlackStop");
Storyboard.SetTargetProperty(DA, new PropertyPath("Offset"));
Storyboard.SetTargetProperty(DA2, new PropertyPath("Offset"));
sb.Duration = Duration;
sb.Completed += sb_Completed;
sb.Begin(this);
if (isPlayer1)
{
Player1.Play();
}
else // Player2
{
Player2.Play();
}
}
catch (Exception)
{
}
}
void sb_Completed(object sender, EventArgs e)
{
if (isPlayer1)
{
Player1.OpacityMask = null;
isPlayer1 = false;
Player2.Stop();
Player2.Source = null;
}
else // Player2
{
Player2.OpacityMask = null;
isPlayer1 = true;
Player1.Stop();
Player1.Source = null;
}
Debug.WriteLine("************** END ANIMATION ***************************************");
}
public void Stop()
{
if (Player1.IsEnabled)
Player1.Stop();
if (Player2.IsEnabled)
Player2.Stop();
}
}
UPDATE:
The same problem happens after I apply shader effect. So video goes well before it and after this it is jumping/freezing. It seems that we have somehow to reset MedieElement or?
private void Button_Click_1(object sender, RoutedEventArgs e)
{
TransitionEffect[] effectGroup = transitionEffects[1];
TransitionEffect effect = effectGroup[1];
DoubleAnimation da = new DoubleAnimation(0.0, 1.0, new Duration(TimeSpan.FromSeconds(2.0)), FillBehavior.HoldEnd);
da.AccelerationRatio = 0.5;
da.DecelerationRatio = 0.5;
da.Completed += da_Completed;
effect.BeginAnimation(TransitionEffect.ProgressProperty, da);
VisualBrush vb = new VisualBrush(this.Player1);
vb.Viewbox = new Rect(0, 0, this.Player1.ActualWidth, this.Player1.ActualHeight);
vb.ViewboxUnits = BrushMappingMode.Absolute;
effect.OldImage = vb;
this.Player1.Effect = effect;
}

Categories