I am working with Modern UI and attempting to make a dialog box that asks a question and then waits for a response. I can do this with messagebox but though I would try using modern UI. I am unsure of how to get the button clicked value.
if (testapp.linkvalue != "NULL")
{
var v = new ModernDialog
{
Title = "my test",
Content = "pewpew lazers rule. If you agree click ok"
};
v.Buttons = new Button[] { v.OkButton, v.CancelButton };
var r = v.ShowDialog();
if (????????????????)
{
MessageBox.Show("ok was clicked");
}
else
{
MessageBox.Show("cancel was clicked");
}
}
if (testapp.linkvalue != "NULL")
{
var v = new ModernDialog
{
Title = "my test",
Content = "pewpew lazers rule. If you agree click ok"
};
v.OkButton.Click += new RoutedEventHandler(OkButton_Click);
v.Buttons = new Button[] { v.OkButton, v.CancelButton };
var r = v.ShowDialog();
}
//And Then Create OkButtonClick
private void OkButton_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("ok was clicked");
}
private void CommonDialog_Click(object sender, RoutedEventArgs e)
{
var dlg = new ModernDialog {
Title = "Common dialog",
Content = new LoremIpsum()
};
dlg.Buttons = new Button[] { dlg.OkButton, dlg.CancelButton};
dlg.ShowDialog();
this.dialogResult.Text = dlg.DialogResult.HasValue ? dlg.DialogResult.ToString() : "<null>";
this.dialogMessageBoxResult.Text = dlg.MessageBoxResult.ToString();
}
It might be another solution using extension method.
var r = v.ShowDialogOKCancel();
if (r==MessageBoxResult.OK)
{
MessageBox.Show("ok was clicked");
}
else
{
MessageBox.Show("cancel was clicked");
}
static class ModernDialogExtension
{
static MessageBoxResult result;
public static MessageBoxResult ShowDialogOKCancel(this FirstFloor.ModernUI.Windows.Controls.ModernDialog modernDialog)
{
result = MessageBoxResult.Cancel;
modernDialog.OkButton.Click += new RoutedEventHandler(OkButton_Click);
modernDialog.Buttons = new Button[] { modernDialog.OkButton, modernDialog.CloseButton };
modernDialog.ShowDialog();
return result;
}
private static void OkButton_Click(object sender, RoutedEventArgs e)
{
result = MessageBoxResult.OK;
}
}
Related
I created in the Loaded event of the main page, a List with some objects of my class "Regioni" and "Musei"
Then I added these items in a ListView, and SelectedItem event recovery the selected object and take it in a new page
private void Page_Loaded(object sender, RoutedEventArgs e)
{
reg.Add(
new Regioni
{
NomeRegione = "Toscana",
NomeProvincia = "Firenze"
});
reg.Add(
new Regioni
{
NomeRegione = "Toscana",
NomeProvincia = "Prato"
});
var gruppi = reg.OrderBy(x => x.NomeRegione).GroupBy(x => x.NomeRegione);
Museum.Source = gruppi;
mus.Add(
new Musei
{
NomeMuseo = "Galleria degli Uffizi",
Paese = "Firenze",
NumeroTel = "055294883",
IndirizzoEmail = "mbac-sspsae-fi#beniculturali.it",
PrezzoBiglietto = "8 € Intero, 4€ Ridotto\r\nGratuito inferiore 18 anni",
Apertura = "Da martedì a domenica,\r\nore 8,15-18,50 Chiusura: Lunedi,Capodanno,Natale,1° Maggio.",
IndirizzoWeb = "http://uffizi.firenze.it/",
Immagine="Assets/Immagini/galleria-uffizi1.jpg",
});
}
private async void ListView_ItemClick_TuttiMusei(object sender, ItemClickEventArgs e)
{
var NuovoMuseo = (Musei)e.ClickedItem;
this.Frame.Navigate(typeof(DettaglioMuseo), NuovoMuseo);
}
Why when I insert the object into the new page "DettaglioMuseo", and go back on the main page, in the ListView I find the same items twice?
This happens because the Loaded-event fires again and adds the items again.
So you should check if your Regionis already exist before adding them:
private void Page_Loaded(object sender, RoutedEventArgs e)
{
AddIfNotExists("Toscana", "Firenze");
AddIfNotExists("Toscana", "Prato");
var gruppi = ...
...
}
private void AddIfNotExists(string regione, string provincia)
{
if (!reg.Any(r => r.NomeProvincia == regione && r.NomeProvincia == provincia))
{
reg.Add(new Regioni { NomeRegione = regione, NomeProvincia = provincia });
}
}
I am going to implement custom confirmation dialog in OnBackKeyPress method. It is easy to do with native message box:
protected override void OnBackKeyPress(CancelEventArgs e)
{
base.OnBackKeyPress(e);
MessageBoxResult result = MessageBox.Show("Text");
if(result==MessageBoxResult.OK)
{
e.Cancel = true;
}
}
It works, but I dislike limitation with two buttons so I am looking for something else.
I have checked WPtoolkit:
private bool m_cansel = false;
protected override void OnBackKeyPress(CancelEventArgs e)
{
base.OnBackKeyPress(e);
if (!m_cansel)
{
e.Cancel = true;
m_cansel = true;
var messageBox = new CustomMessageBox
{
Title = "Title",
Message = "Message",
RightButtonContent = "aas",
IsLeftButtonEnabled = false,
};
messageBox.Dismissed += (sender, args) =>
{
};
messageBox.Show();
}
}
And Coding4Fun:
private bool m_cansel = false;
protected override void OnBackKeyPress(CancelEventArgs e)
{
base.OnBackKeyPress(e);
if (!m_cansel)
{
e.Cancel = true;
m_cansel = true;
var messageBox = new MessagePrompt
{
Title = "Title",
Message = "Message",
};
messageBox.Completed += (sender, args) =>
{
//throw new NotImplementedException();
};
messageBox.Show();
}
Both looks good, but don't work in OnBackKeyPress method (show and immediately disappear without any my action).
Moreover, I've tried XNA:
private bool m_cansel = false;
protected override void OnBackKeyPress(CancelEventArgs e)
{
base.OnBackKeyPress(e);
if (!m_cansel)
{
e.Cancel = true;
m_cansel = true;
Guide.BeginShowMessageBox("Version of Windows", "Pick a version of Windows.",
new List<string> {"Vista", "Seven"}, 0, MessageBoxIcon.Error,
asyncResult =>
{
int? returned = Guide.EndShowMessageBox(asyncResult);
}, null);
}
}
It works as I expected (has customs in OnBackKeyPress method), but I don't sure that using XNA inside Silverlight app is good practice.
So, I am looking a way to use WPtoolkit or Coding4Fun windows inside OnBackKeyPress method or any explanation about using XNA inside Silverlight app (any recomendation or info about approval such kind app by store).
Just use the dispatcher to delay the messagebox until you get out of the OnBackKeyPress event, and it should work:
private bool m_cansel = false;
protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
{
base.OnBackKeyPress(e);
if (!m_cansel)
{
e.Cancel = true;
m_cansel = true;
var messageBox = new CustomMessageBox
{
Title = "Title",
Message = "Message",
RightButtonContent = "aas",
IsLeftButtonEnabled = false,
};
messageBox.Dismissed += (sender, args) =>
{
};
Dispatcher.BeginInvoke(messageBox.Show);
}
}
Alternatively, you can use the BackKeyPress event instead of overriding the OnBackKeyPress method. This way, you don't need to use the dispatcher:
privatevoid Page_BackKeyPress(object sender, System.ComponentModel.CancelEventArgs e)
{
if (!m_cansel)
{
e.Cancel = true;
m_cansel = true;
var messageBox = new CustomMessageBox
{
Title = "Title",
Message = "Message",
RightButtonContent = "aas",
IsLeftButtonEnabled = false,
};
messageBox.Dismissed += (s, args) =>
{
};
messageBox.Show();
}
}
And in the XAML:
BackKeyPress="Page_BackKeyPress"
I have to disply the number of dragged files count on mouse cursor while dragging document from file system to my form.
I have done the following code, but I can not change the drag cursor. Please let me know the best way to do this
private void tbDisplayFileContents_PreviewDragOver(object sender, DragEventArgs args)
{
if (IsSingleFile(args) != null)
{
tbDisplayFileContents_PreviewDrop(sender, args);
}
else
{
// args.Effects = DragDropEffects.None;
}
Mouse.SetCursor(Cursors.Hand);
Icon ico = new Icon(string.Concat("1365516094_10371.ico"));
tbDisplayFileContents.Cursor = GenerateCursor.CreateCursor(ico, true, new System.Drawing.Color());
args.Handled = true;
}
private void tbDisplayFileContents_PreviewDrop(object sender, DragEventArgs args)
{
args.Handled = true;
string files = string.Empty;
string[] fileName = IsSingleFile(args);
if (fileName == null) return;
isDrag = true;
DoEvents();
for (int i = 0; i < fileName.Length; i++)
{
if (i == 0)
{
files = string.Concat("1] ", fileName[i]);
}
else
{
int j = i + 1;
files = string.Concat(files, Environment.NewLine, j, "] ", fileName[i]);
}
}
lblfileName.Content = files;
}
private string[] IsSingleFile(DragEventArgs args)
{
if (args.Data.GetDataPresent(DataFormats.FileDrop, true))
{
string[] fileNames = args.Data.GetData(DataFormats.FileDrop, true) as string[];
if (fileNames.Length != 0)
{
if (File.Exists(fileNames[0]))
{
// At this point we know there is a single file.
return fileNames;
}
}
}
return null;
}
#endregion
#region -------Events--------
private void btnClear_Click(object sender, RoutedEventArgs e)
{
lblfileName.Content = string.Empty;
}
#endregion
private void tbDisplayFileContents_PreviewDragEnter(object sender, DragEventArgs e)
{
e.Effects = DragDropEffects.None;
}
public static void DoEvents()
{
Application.Current.Dispatcher.Invoke(DispatcherPriority.Background,
new Action(delegate
{
Icon ico = new Icon(string.Concat("1365516094_10371.ico"));
Mouse.OverrideCursor = GenerateCursor.CreateCursor(ico, true, new System.Drawing.Color());
}));
}
I have used GiveFeedBack event as follows
private void tbDisplayFileContents_GiveFeedback(object sender, GiveFeedbackEventArgs e)
{
if (e.Effects == DragDropEffects.Copy)
{
e.UseDefaultCursors = false;
// Mouse.SetCursor(Cursors.Hand);
Icon ico = new Icon(string.Concat("1365516094_10371.ico"));
//Mouse.Cursor = GenerateCursor.CreateCursor(ico, true, new System.Drawing.Color());
Mouse.SetCursor(GenerateCursor.CreateCursor(ico, true, new System.Drawing.Color()));
}
else
e.UseDefaultCursors = true;
e.Handled = true;
}
It is working for form to form dragging but it is not working for the contents(file) which is dragged from outside form e.g files from Desktop.
I miss the GiveFeedback event in your code, which is used to modify the Mouse cursor while drag and drop operations.
I have created a virtual keyboard, the keyboard pops up for wpf textbox controls. How can I make the keyboard pops out when clicking on a textbox inside a web page?
the logic for displaying a textbox is given below:
static void TouchScreenKeyboardPropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
FrameworkElement host = sender as FrameworkElement;
if (host != null)
{
host.GotFocus += new RoutedEventHandler(OnGotFocus);
host.LostFocus += new RoutedEventHandler(OnLostFocus);
}
}
static void OnGotFocus(object sender, RoutedEventArgs e)
{
Control host = sender as Control;
if (sender == typeof(TextBox))
{
_PreviousTextBoxBackgroundBrush = host.Background;
_PreviousTextBoxBorderBrush = host.BorderBrush;
_PreviousTextBoxBorderThickness = host.BorderThickness;
host.Background = Brushes.Yellow;
host.BorderBrush = Brushes.Red;
host.BorderThickness = new Thickness(4);
}
_CurrentControl = host;
if (_InstanceObject == null)
{
FrameworkElement ct = host;
while (true)
{
if (ct is Window)
{
((Window)ct).LocationChanged += new EventHandler(TouchScreenKeyboard_LocationChanged);
((Window)ct).Activated += new EventHandler(TouchScreenKeyboard_Activated);
((Window)ct).Deactivated += new EventHandler(TouchScreenKeyboard_Deactivated);
break;
}
if(ct.Parent != null)
ct = (FrameworkElement)ct.Parent;
}
_InstanceObject = new TouchScreenKeyboard();
_InstanceObject.AllowsTransparency = true;
_InstanceObject.WindowStyle = WindowStyle.None;
_InstanceObject.ShowInTaskbar = false;
_InstanceObject.ShowInTaskbar = false;
_InstanceObject.Topmost = true;
host.LayoutUpdated += new EventHandler(tb_LayoutUpdated);
}
}
static void TouchScreenKeyboard_Deactivated(object sender, EventArgs e)
{
if (_InstanceObject != null)
{
_InstanceObject.Topmost = false;
}
}
static void TouchScreenKeyboard_Activated(object sender, EventArgs e)
{
if (_InstanceObject != null)
{
_InstanceObject.Topmost = true;
}
}
static void TouchScreenKeyboard_LocationChanged(object sender, EventArgs e)
{
syncchild();
}
static void tb_LayoutUpdated(object sender, EventArgs e)
{
syncchild();
}
static void OnLostFocus(object sender, RoutedEventArgs e)
{
Control host = sender as Control;
host.Background = _PreviousTextBoxBackgroundBrush;
host.BorderBrush = _PreviousTextBoxBorderBrush;
host.BorderThickness = _PreviousTextBoxBorderThickness;
if (_InstanceObject != null)
{
_InstanceObject.Close();
_InstanceObject = null;
}
}
#endregion
}
private static void syncchild()
{
if (_CurrentControl != null && _InstanceObject != null)
{
Point virtualpoint = new Point(0, _CurrentControl.ActualHeight + 3);
Point Actualpoint = _CurrentControl.PointToScreen(virtualpoint);
if (WidthTouchKeyboard + Actualpoint.X > SystemParameters.VirtualScreenWidth)
{
double difference = WidthTouchKeyboard + Actualpoint.X - SystemParameters.VirtualScreenWidth;
_InstanceObject.Left = Actualpoint.X - difference;
}
else if (!(Actualpoint.X > 1))
{
_InstanceObject.Left = 1;
}
else
_InstanceObject.Left = Actualpoint.X;
_InstanceObject.Top = Actualpoint.Y;
_InstanceObject.Show();
}
}
private static void SetKeyInBrowser(string key)
{
var elementName = (((mshtml.HTMLDocument)(dom)).activeElement).id;
if (elementName != null)
{
var existingText = dom.getElementById(elementName).getAttribute("value");
if (existingText == null)
{
existingText = "";
}
//if it's a backspace.
if (isBackspace)
{
existingText = existingText.ToString().Remove(existingText.ToString().Length - 1);
dom.getElementById(elementName).setAttribute("value", existingText.ToString());
}
else if (key.Length != 0)
{
dom.getElementById(elementName).setAttribute("value", existingText.ToString() + key[key.Length - 1]);
}
}
isBackspace = false;
}
You need to use javascript for that. You need to know when that textfield is focused like this:
Check if focus is on a textfield
And then once the focused event is fired on JavaScript you should call your WPF function for showing the keyboard up. Here's useful hints:
How to programmaticaly check if a text input box inside a web page loaded in WPF Browser has focus?
I have been looking all over the Internet for this and have found similar, but none of it will work for me. Everything I have found assumes the listbox is on the main form and not the secondary form, or the code is for an older version of C# or Visual Studio (I am using VS2008).
I am creating a web browser that has a button on the main form (called frmMyBrowser) to open a dialog (frmBookmarks) with a listbox (lstBookmark) with bookmarked URLs. I need to be able to double click on an item (the bookmarked URL) and have the text pasted into the address bar (cmbAddress) of the main form.
Any help would be GREATLY appreciated.
I figured out that if I create the window at runtime, I can get it to work. In case anyone is interested, the code I used is below.
public void frmMyBrowser_ShowFavorites(object sender, EventArgs e)
{
frmFavorites.ShowIcon = false;
frmFavorites.ShowInTaskbar = false;
frmFavorites.MinimizeBox = false;
frmFavorites.MaximizeBox = false;
frmFavorites.ControlBox = false;
frmFavorites.Text = "Bookmarks";
frmFavorites.Width = 500;
frmFavorites.Height = 350;
frmFavorites.Controls.Add(lstFavorites);
frmFavorites.Controls.Add(btnRemoveFavorite);
frmFavorites.Controls.Add(btnAddFavorite);
frmFavorites.Controls.Add(btnCloseFavorites);
frmFavorites.Controls.Add(txtCurrentUrl);
lstFavorites.Width = 484;
lstFavorites.Height = 245;
btnRemoveFavorite.Location = new Point(8, 280);
btnAddFavorite.Location = new Point(8, 255);
btnCloseFavorites.Location = new Point(400, 255);
txtCurrentUrl.Location = new Point(110, 255);
txtCurrentUrl.Size = new Size(255, 20);
btnAddFavorite.Text = "Add";
btnRemoveFavorite.Text = "Remove";
btnCloseFavorites.Text = "Close";
txtCurrentUrl.Text = wbBrowser.Url.ToString();
btnAddFavorite.Click += new EventHandler(btnAddFavorite_Click);
btnRemoveFavorite.Click += new EventHandler(btnRemoveFavorite_Click);
frmFavorites.Load += new EventHandler(frmFavorites_Load);
btnCloseFavorites.Click += new EventHandler(btnCloseFavorites_Click);
lstFavorites.MouseDoubleClick += new MouseEventHandler(lstFavorites_MouseDoubleClick);
frmFavorites.Show();
}
public void btnCloseFavorites_Click(object sender, EventArgs e)
{
if (lstFavorites.Items.Count > 0)
{
using (StreamWriter writer = new System.IO.StreamWriter(#Application.StartupPath + "\\favorites.txt"))
{
for (int i = 0; i < lstFavorites.Items.Count; i++)
{
writer.WriteLine(lstFavorites.Items[i].ToString());
}
writer.Close();
}
}
frmFavorites.Hide();
}
public void btnAddFavorite_Click(object sender, EventArgs e)
{
string strFavoriteAddress = wbBrowser.Url.ToString();
if (!lstFavorites.Items.Contains(strFavoriteAddress))
{
lstFavorites.Items.Add(strFavoriteAddress);
MessageBox.Show("Favorite Added", "Message");
}
else if (lstFavorites.Items.Contains(strFavoriteAddress))
{
MessageBox.Show("This site already exists in your Favorites list!", "Error");
}
else
{
}
}
public void btnRemoveFavorite_Click(object sender, EventArgs e)
{
try
{
lstFavorites.Items.RemoveAt(lstFavorites.SelectedIndices[0]);
}
catch
{
MessageBox.Show("You need to select an item", "Error");
}
}
public void frmFavorites_Load(object sender, EventArgs e)
{
try
{
using (StreamReader reader = new System.IO.StreamReader(#Application.StartupPath + "\\favorites.txt"))
{
while (!reader.EndOfStream)
{
for (int i = 0; i < 4; i++)
{
string strListItem = reader.ReadLine();
if (!String.IsNullOrEmpty(strListItem))
{
lstFavorites.Items.Add(strListItem);
}
}
}
reader.Close();
}
}
catch
{
MessageBox.Show("An error has occured", "Error");
}
}
private void lstFavorites_MouseDoubleClick(object sender, MouseEventArgs e)
{
string strSelectedAddress = lstFavorites.Text.ToString();
cmbAddress.Text = strSelectedAddress;
wbBrowser.Navigate(strSelectedAddress);
frmFavorites.Hide();
}