Trying to select text in Textbox in Dialog when gaining Focus - c#

I'm trying to select the whole text in a dialog but I'm not able to do so.
I have a class Participant which has a Property Firstname. When I set the participant in my dialog I'm calling a Focus-Method. However, when the dialog is open it's only in focus but not selected.
This is my Focus-Method:
public void FocusSurname()
{
SurnameBox.SelectAll();
SurnameBox.Focus();
Keyboard.Focus(SurnameBox);
}
In the dialog I'm setting my participant as follow:
Participant Participant
{
get { return _participant; }
set
{
_participant = value;
FocusSurname();
}
}
My dialog open sourcecode is pretty much:
public void ShowDialog(object owner)
{
Owner = owner as Window;
ShowDialog();
}
Why is the text not selected? :(
Even when I call FocursSurname in my ShowDialog-Method nothing is changing.

what you are trying to accomplish is view related code (in my opinion). The mvvm guidiance or pattern use (or at least my understanding of it) state that you want to use behaviors or attached properties for that. Means extending xaml functionality to plugin view related behaviors...
I found a stackoverflow question that relates to your topic. Check out if this might help... or try to derive from that solution...
Link:
Initial Focus and Select All behavior
HTH

Bind following event handler method to GotFocus event of the text box
private static void SelectText(object sender, RoutedEventArgs e)
{
var textBox = e.OriginalSource as TextBox;
Keyboard.Focus(textBox);
textBox.SelectAll();
}

Related

How to make correct initialization of ComboBox?

I need show droppeddown combobox after start program.
I need in dropdown style only, not simple style.
This is simple fragment of my program:
private void Form1_Shown(object sender, EventArgs e)
{
CB1.Items.Add("1");
CB1.DropDownStyle = ComboBoxStyle.DropDown;
CB1.DroppedDown = true;
}
But I found the watch sign as cursor till I click on Form in any place.
I guessed that my Form have not fully active state and wait for something.
When I click Form (or combobox or any control) by LBM, it activated fully and all works fine.
Of course the combobox is dropup then, so I need click combobox twice.
Đ•ell me please what is correct initialization of such style combobox without "Cursor = Cursors.Default;"
You can simply wait until cursor is the default:
while (Cursor.Current != Cursors.Default)
{
Application.DoEvents();
}
CB1.Items.Add("1");
CB1.DropDownStyle = ComboBoxStyle.DropDown;
CB1.DroppedDown = true;
Application.DoEvents simply process messages from the window queue, so you can process message until you get that cursor is the default. In that moment, you can drop down your control without problem.
If you prefer, create a extension method for the Form:
public static class FormExtends
{
public static void WaitToDefaultCursor(this Form form)
{
while (Cursor.Current != Cursors.Default)
{
Application.DoEvents();
}
}
}
And use it:
this.WaitToDefaultCursor();
CB1.Items.Add("1");
CB1.DropDownStyle = ComboBoxStyle.DropDown;
CB1.DroppedDown = true;
NOTE: I use Cursor.Default but not to change the cursor. The form is processing messages and it's difficult to select a good moment to drop down the control.

Navigating to specific ContentFrame when refreshing NavigationView

I have an app which uses a NavigationView as a UI-control.
Now I have a SettingsPage where I can change the language of my UI between german and english.
I change the language with this code:
public static void German()
{
Log.Logger.Information("Language = German")
ApplicationLanguages.PrimaryLanguageOverride = "de-DE";
DataCollection.Current.LanguageChangedEvent.LanguageChanged();
}
The last line invokes an EventHandler which in turn invokes the following event on the MainPage.xaml.cs where the NavigationView is located.
public void ChangedLanguage(object source, EventHandlerBase e)
{
if (e.GetStatus())
{
Windows.ApplicationModel.Resources.Core.ResourceContext.GetForCurrentView().Reset();
Windows.ApplicationModel.Resources.Core.ResourceContext.GetForViewIndependentUse().Reset();
Frame.Navigate(this.GetType());
ContentFrame.Navigate(typeof(SettingsPage));
}
}
As it's possible to see I just want to return the user to the SettingsPage after changing the language.
But I always return back to the initial HomePage that I use when starting the app.
The code I use for the NavigationView is derived from the official NavigationView sample provided by Microsoft.
Is there any possible way to do this? The only possible thing I can imagine is to set a flag after the first page loading and then always check if that flag is set. But then I have the problem that I still could only land at the SettingsPage because I would have to make it the else destination for the flag-check.
Would really appreciate a more dynamic way if thats even possible :/
Greeting,
Daniel
The NavigationView sample just is a simple code sample for your reference. You need to make some changes by your requirements.
I just want to return the user to the SettingsPage after changing the language. But I always return back to the initial HomePage that I use when starting the app.
I've used the code on the document to make a code sample for testing. There're two places will cause your question.
First, in the NavView_Loaded event handler, it will always sets the home page as the selected item. But when you change the language, you re-navigate to 'MainPage' and make 'ContentFrame' navigate to 'SettingsPage'. At this time, the On_Navigated event handler will be first called. Then, the NavView_Loaded event handler will be called. That's the reason why your app always will return to home page.
Second, event if the NavigationView's SelectedItem has been set. But the NavigationView's ItemInvoked event will not be fired. So, what you see actually is not home page, it's a blank Frame control. You could use SelectionChanged event instead of ItemInvoked event. The SelectionChanged event will be fired when you set a new value for the NavigationView's SelectedItem. See the following sample:
private void NavView_SelectionChanged(NavigationView sender, NavigationViewSelectionChangedEventArgs args)
{
if (args.IsSettingsSelected)
{
ContentFrame.Navigate(typeof(SettingsPage));
}
else
{
NavView_Navigate(args.SelectedItem as NavigationViewItem);
}
}
Then, let's back to your original question:
I can imagine is to set a flag after the first page loading and then always check if that flag is set. But then I have the problem that I still could only land at the SettingsPage because I would have to make it the else destination for the flag-check.
In my opinion, the flag will not affect you doing other things. You completely could define several flags. Please see my following code snippet for reference:
public static void German()
{
Log.Logger.Information("Language = German")
ApplicationLanguages.PrimaryLanguageOverride = "de-DE";
ApplicationData.Current.LocalSettings.Values["IsSwitchingLanguage"] = true;
DataCollection.Current.LanguageChangedEvent.LanguageChanged();
}
In your MainPage.xaml.cs:
public void ChangedLanguage(object source, EventHandlerBase e)
{
if (e.GetStatus())
{
Windows.ApplicationModel.Resources.Core.ResourceContext.GetForCurrentView().Reset();
Windows.ApplicationModel.Resources.Core.ResourceContext.GetForViewIndependentUse().Reset();
Frame.Navigate(this.GetType());
}
}
In NavView_Loaded event handler, I made some changes:
private void NavView_Loaded(object sender, RoutedEventArgs e)
{
......
foreach (NavigationViewItemBase item in NavView.MenuItems)
{
var IsSwitchingLanguage = ApplicationData.Current.LocalSettings.Values["IsSwitchingLanguage"];
if (IsSwitchingLanguage != null)
{
if ((bool)IsSwitchingLanguage)
{
NavView.SelectedItem = NavView.SettingsItem as NavigationViewItem;
ApplicationData.Current.LocalSettings.Values["IsSwitchingLanguage"] = false;
break;
}
}
if (item is NavigationViewItem && item.Tag.ToString() == "home")
{
NavView.SelectedItem = item;
break;
}
}
......
}

How to update a ComboBox from a window when closing another window?

First of all, I want to apologize for:
The software is in Portuguese.
The software is ugly as hell. It is for a school project and we decided to focus more on the funcionality than the design (I know, it's wrong, but we had to choose...)
I read update combobox from another form in c# but I didn't understand what happened.
That said, let's go to the issue.
I have this window:
If I click the button marked in red:
This will open:
This is supposed to be a software for a market. The first window is responsible to order more thing to the inventory. The second window is responsible to add a supplier into the system.
The combobox shows all the suppliers on the system. I want when I finish adding a supplier on the second window after I clicked on the button highlighted with the red rectangle, the combobox will update automatically with the new data.
I used a "Update" button with this code:
this.tb_FornecedorTableAdapter.Fill(this.tccDataSet.tb_Fornecedor);
It worked, but I tried to use on FormClosing, FormClosed and Deactivate events on the other windows and it didn't work at all (I modified the "this" on the code to a lot of this and it didn't help me). Is there a way to do what I want?
If the ComboBox is updated with the data from SQL Server then you can try this:
// When button Adicionar is clicked
private void buttonAdd_Click(object sender, EventArgs e)
{
using(Form formAdd = new Form()) // This is the Gerenciar Fornecedor form
{
formAdd.ShowDialog(this); // Show the form. The next statement will not be executed until formAdd is closed
// Put the your code to update the ComboBox items here
}
}
In the first window declare a public methord:
public void RefreshCombo()
{
this.tb_FornecedorTableAdapter.Fill(this.tccDataSet.tb_Fornecedor);
}
Then in the first window add button click event
WindowB window=new WindowB(this);
WindowB.Show();
Then in the child window add a ctor method:
private WindowA windowParent;
public WindowB(WindowA parent)
{
InitializeComponent();
this.windowParent=parent;
}
In WindowB FormClosing Event
this.windowParent.RefreshCombo()
What you can do in this case is to add a property on the child form to store the combo box value and populate it when the combo box value changes. Also, create a method on the child form that will be called from the parent form. It will show the child form and return the combo box value.
public partial class ChildForm : Form
{
public ChildForm()
{
InitializeComponent();
}
private string _comboValue { get; set; }
public string ShowAndGetComboValue()
{
this.ShowDialog();
return _comboValue;
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
_comboValue = comboBox1.SelectedItem.ToString();
}
}
On the parent form, you can then display the child form this way:
ChildForm form = new ChildForm();
string comboValue = form.ShowAndGetComboValue();

C# WinForms showing a control as a dropdown

Gretings
I need to have a custom control for my application. Basically its an expression editing GUI. You have, say, expression:
If variable_x is greater than variable_y
And you can click on "greater than" and change it to other comparator (like, equal to or less than).
The control thus must look like a label, but when you click it, it must show a dropdown (like combobox does) that has a listview inside (or maybe some other control) so that user can choose something. In a sense, i need a combobox without the box itself, replaced by something else (in this case, a label).
I know how to make custom controls, i understand i must somehow DropDown on mouse click or enter keypress, and hook events so that when whatever i dropped has closed, the choice is made, and also somehow track if user clicked elsewhere so i can close this dropdowned control. But i dont know if this is easy to do (some built-in method exists) or i have to do it all myself? Dont want to redevelop the wheel....
Please tell me if there are easy ways to do this.
Thanks!
You can extend the ComboBox control to update the DropDownStyle on Enter and LostFocus events.
public partial class MyComboBox : ComboBox
{
public MyComboBox()
{
InitializeComponent();
this.Dock = DockStyle.Fill;
this.SelectionChangeCommitted += this.OnComboBoxSelectionChangeCommitted;
this.Enter += this.OnControlEnter;
this.LostFocus += this.OnComboBoxLostFocus;
}
private void OnControlEnter(object sender, EventArgs e)
{
this.DropDownStyle = ComboBoxStyle.DropDownList;
}
private void OnComboBoxLostFocus(object sender, EventArgs e)
{
this.DropDownStyle = ComboBoxStyle.Simple;
}
private void OnComboBoxSelectionChangeCommitted(object sender, EventArgs e)
{
// Notify to update other controls that depend on the combo box value
}
}

How to hide the tool tips

I am having a treeview with some nodes. I am also having a panel. I have taken some usercontrol forms and i will load those usercontrols when corresponding node is selected from the child hood. Now what i need is have some validations like if i left the text box empty i will have some tooltips displayed to the user. Suppose if i click on first node i will have a user control loaded. With out giving any values if i hit ok i will have some tool tips as follows
Now if i select the second node from the tree still the tooltips getting displayed i would like to hide those
Any Help please
my code for rasing error tooltips is as shown below
public class TestClass
{
public void RequiredText(TextBox txtTemp, ToolTip newtoolTip)
{
if (txtTemp.Text != string.Empty)
{
txtTemp.BackColor = System.Drawing.Color.White;
newtoolTip.Hide(txtTemp);
}
else
{
txtTemp.BackColor = System.Drawing.Color.Tomato;
newtoolTip.Show("Required", txtTemp);
}
}
}
But this was done in the use control form.
I haven't yet mastered the art of reverse-engineering code from a screenshot. I'm guessing that you don't dispose the previous user control when you select a new one. Allowing the tool tip to stay visible. Use code like this:
private UserControl currentView;
public void SelectView(UserControl view) {
if (currentView == view) return;
if (currentView != null) currentView.Dispose();
if (view != null) this.Controls.Add(view);
currentView = view;
}
And call SelectView() from the TreeView's AfterSelect event handler.
Have you tried the Hide method?
http://dotnetperls.com/tooltip
Got the answer just written Usrcntrl_Leave event for every user control as
private void usrcntrlPPD_Leave(object sender, EventArgs e)
{
this.Dispose();
}
This solved my problem :)
private void timer1(object sender, EventArgs e)
{
count++;
if (count == 2)
{
toolTMensaje.SetToolTip(textBox1,"");
toolTMensaje.Hide(textBox1);
count = 0;
timer1.Stop();
}
}

Categories