OK so I have to work with lots of toggle button and textbox, so I named them in such way that adding letter "Q" to button's name will give name of the textbox that the button corresponds to. I have link all the button to the same method on checked event, and using this naming mechanism I, hope to manipulate the textbox corresponding the button.
What I have done till now is, generate an name of the textbox in string format. But i don't know to how to use this string to manipulate the textbox.
private void OnbuttonClick(object sender, RoutedEventArgs e)
{
ToggleButton tb = (ToggleButton)sender;
if(tb.IsChecked==true)
{
string tbnam = ((ToggleButton)sender).Name;
string name2 = tbnam + "Q";
?????? (what happens from this point onward)
}
}
"name2" is the name of textbox that corresponds to the toggle button of name "tbnam".
I hope the I have made the problem clear.
In WPF, a much better way to do this would to expose a collection of objects in the viewmodel, and display in the UI with an ItemsControl with an ItemTemplate that would dynamically create as many iterations of ToggleButton/TextBox pairs as needed. I'd be happy to go into how to do that, if you're interested.
But for now, you can get your code working using the FindName(string) method:
private void Button_Click(object sender, RoutedEventArgs e)
{
ToggleButton tb = (ToggleButton)sender;
if (tb.IsChecked == true)
{
string name2 = tb.Name + "Q";
TextBox tbox = FindName(name2) as TextBox;
// Check to see if tbox is null, do stuff with it
}
}
I have a custom control containing a textbox and a button. I use the custom control as an editing control for a specific column in an ObjectListView.
On CellEditStarting event I do:
private void datalistViewProducts_CellEditStarting(object sender, CellEditEventArgs e)
{
var ctl = (MyCustomControl)e.Control;
e.Control = ctl;
}
The ObjectListView's ConfigureControl method already calls the control's Select method. It works fine if I have a usercontrol inheriting directly from a standard TextBox.
So I added the following code to my usercontrol:
public new void Select()
{
textBox.Select();
}
However, having a usercontrol as described above, the Select method does not move the focus to the textbox.
What am I missing here?
You can create a method in CustomUserControl, say FocusControl(string controlName)
and then call this method to focus the control in Custom Control.
Create the method in your custom User Control-
public void FocusControl(string controlName)
{
var controls = this.Controls.Find(controlName, true);
if (controls != null && controls.Count() == 1)
{
controls.First().Focus();
}
}
Call this method-
//textBox1 is the name of your focussing control in Custom User Control
userControl11.FocusControl("textBox1");
The only way that made it finally work was to add the following code in the usercontrol:
protected override void OnEnter(EventArgs e)
{
base.OnEnter(e);
textBox.Select();
}
I have a field that currently changes text on a mouse click. This field is on multiple pages of my report, but clicking it only changes the text for that page. Here is my code for that:
const string sShowDetail2 = "Show Cumulative";
const string sHideDetail2 = "Hide Cumulative";
ArrayList expandedValues2 = new ArrayList();
// This function returns a value indicating whether a certain
// category's details should be expanded.
bool ShouldShowDetail2(int CategoryID)
{
return expandedValues2.Contains(CategoryID);
}
private void lbShowHide2_BeforePrint(object sender, PrintEventArgs e)
{
XRLabel label = (XRLabel)sender;
if (ShouldShowDetail2((int)label.Tag))
{
label.Text = sHideDetail2;
}
else
{
label.Text = sShowDetail2;
}
}
private void lbShowHide2_PreviewClick(object sender, PreviewMouseEventArgs e)
{
// Obtain the category's ID stored in the label's Tag property.
int index = (int)e.Brick.Value;
// Determine whether the current category's details are shown.
bool showDetail2 = ShouldShowDetail2(index);
// Toggle the visibility of the category's details.
if (showDetail2)
{
expandedValues2.Remove(index);
}
else
{
expandedValues2.Add(index);
}
Now I have another field that I need to simply toggle all instances of the field(every page) on click. I do not need it to read the tag of the particular one I clicked because it will be changing all of them at the same time. My problem is that I don't know how to get them all to change on mouse click. How could I modify the code above to change all instances of the label?
Here is something you could try
private void ChangeXRLabels(Control control)
{
foreach(Control childControl in control.Controls)
{
XRLabel label = childControl as XRLabel;
if(label != string.Empty)
label.Text = "Your Text Value goes Here";
else if(childControl.Controls.Count > 0)
ChangeXRLabels(childControl);
}
}
C#, .NET 4.0, VS2010.
New to WPF. I have a ComboBox on my MainWindow. I hooked the SelectionChanged event of said combo box. However, if I examine the value of the combo box in the event handler, it has the old value. This sounds more like a "SelectionChanging" event, than a SelectionChanged event.
How do I get the new value of the ComboBox after the selection has actually happend?
Currently:
this.MyComboBox.SelectionChanged += new SelectionChangedEventHandler(OnMyComboBoxChanged);
...
private void OnMyComboBoxChanged(object sender, SelectionChangedEventArgs e)
{
string text = this.MyComboBox.Text;
}
Note, I get the same behaviour if I use the object being passed in the event args, e.g. e.OriginalSource.
According to MSDN, e.AddedItems:
Gets a list that contains the items that were selected.
So you could use:
private void OnMyComboBoxChanged(object sender, SelectionChangedEventArgs e)
{
string text = (e.AddedItems[0] as ComboBoxItem).Content as string;
}
You could also use SelectedItem if you use string values for the Items from the sender:
private void OnMyComboBoxChanged(object sender, SelectionChangedEventArgs e)
{
string text = (sender as ComboBox).SelectedItem as string;
}
or
private void OnMyComboBoxChanged(object sender, SelectionChangedEventArgs e)
{
string text = ((sender as ComboBox).SelectedItem as ComboBoxItem).Content as string;
}
Since both Content and SelectedItem are objects, a safer approach would be to use .ToString() instead of as string
The correct value to check here is the SelectedItem property.
A ComboBox is a composite control with two of its parts being:
The Text Part: the value in the this part corresponds to the Text property of the ComboBox.
The Selector Part (i.e. the "drop-down" part): The selected item in this part corresponds to the SelectedItem property.
The image above was taken immediately after the ComboBox was expanded (i.e. before selecting a new value). At this point both Text and SelectedItem are "Info", assuming the ComboBox items were strings. If the ComboBox items were instead all the values of an Enum called "LogLevel", SelectedItem would currently be LogLevel.Info.
When an item in the drop-down is clicked on, the value of SelectedItem is changed and the SelectionChanged event is raised. The Text property isn't updated yet, though, as the Text Part isn't updated until after the SelectionChanged handler is finished. This can be observed by putting a breakpoint in the handler and looking at the control:
Since the Text Part hasn't been updated at this point, the Text property returns the previously selected value.
Use the DropDownClosed event instead of selectionChanged if you want the current value of the combo box.
private void comboBox_DropDownClosed(object sender, EventArgs e)
{
MessageBox.Show(comboBox.Text)
}
Is really that simple.
This worked for me:
private void AppName_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ComboBoxItem cbi = (ComboBoxItem)AppName.SelectedItem;
string selectedText = cbi.Content.ToString();
}
This worked for me:
private void OnMyComboBoxChanged(object sender, SelectionChangedEventArgs e)
{
var text = ((sender as ComboBox).SelectedItem as ComboBoxItem).Content as string;
}
Following event is fired for any change of the text in the ComboBox (when the selected index is changed and when the text is changed by editing too).
<ComboBox IsEditable="True" TextBoxBase.TextChanged="cbx_TextChanged" />
private void OnMyComboBoxChanged(object sender, SelectionChangedEventArgs e)
{
string newItem = ((DataRowView) e.AddedItems[0]).Row.ItemArray[0].ToString();
}
The second option didn't work for me because the .Text element was out of scope (C# 4.0 VS2008). This was my solution...
string test = null;
foreach (ComboBoxItem item in e.AddedItems)
{
test = item.Content.ToString();
break;
}
If you really need the SelectionChanged event, then the best answer is SwDevMan81's answer. However, if you are starting with WPF, then you might want to learn how to do things the WPF way, which is different than the old Windows Forms days that used to rely on events like SelectionChanged, with WPF and Model View ViewModel pattern, you should use bindings. Here is a code example:
// In the Views folder: /Views/MyWindow.xaml:
// ...
<ComboBox ItemsSource="{Binding MyViewModel.MyProperties, RelativeSource={RelativeSource AncestorType=Window}}"
SelectedItem="{Binding MyViewModel.MyProperty , RelativeSource={RelativeSource AncestorType=Window}}" />
// ...
// In the Views folder: /Views/MyWindow.xaml.cs:
public partial class MyWindow : Window
{
public MyViewModelClass MyViewModel {
get { return _viewModel; }
private set { _viewModel = value;}
}
public MyWindow()
{
MyViewModel.PropertyChanged += MyViewModel_PropertyChanged;
}
void MyViewModel_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
if (e.PropertyName == "MyProperty")
{
// Do Work
// Put your logic here!
}
}
}
using System.ComponentModel;
// In your ViewModel folder: /ViewModels/MyViewModelClass.cs:
public class MyViewModelClass : INotifyPropertyChanged
{
// INotifyPropertyChanged implementation:
private void NotifyPropertyChanged(string propertyName = "") { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } }
public event PropertyChangedEventHandler PropertyChanged;
// Selected option:
private string _myProperty;
public string MyProperty {
get { return _myProperty; }
set { _myProperty = value; NotifyPropertyChanged("MyProperty"); }
}
// Available options:
private List<string> _myProperties;
public List<string> MyProperties {
get { return _myProperties; }
set { _myProperties = value; NotifyPropertyChanged("MyProperties"); }
}
}
private void indBoxProject_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
int NewProjID = (e.AddedItems[0] as kProject).ProjectID;
this.MyProject = new kProject(NewProjID);
LoadWorkPhase();
}
The use of the e.AddedItems[0] as kProject where kProject is a class that holds the data worked for me as it was defaulting to the RemovedItems[0] before I have made this explicit distinction. Thanks SwDevMan81 for the initial information that answered this question for me.
I needed to solve this in VB.NET. Here's what I've got that seems to work:
Private Sub ComboBox1_SelectionChanged(ByVal sender As System.Object, ByVal e As System.Windows.Controls.SelectionChangedEventArgs) Handles ComboBox_AllSites.SelectionChanged
Dim cr As System.Windows.Controls.ComboBoxItem = ComboBox1.SelectedValue
Dim currentText = cr.Content
MessageBox.Show(currentText)
End Sub
It's weird that SelectedItem holds the fresh data, whereas SelectedValue doesn't. Sounds like a bug to me. If your items in the Combobox are objects other than ComboBoxItems, you will need something like this: (my ComboBox contains KeyValuePairs)
var selectedItem = (KeyValuePair<string, string>?)(sender as ComboBox).SelectedItem;
if (!selectedItem.HasValue)
return;
string selectedValue = selectedItem.Value.Value; // first .Value gets ref to KVPair
ComboBox.SelectedItem can be null, whereas Visual Studio keeps telling me that a KeyValuePair can't be null. That's why I cast the SelectedItem to a nullable KeyValuePair<string, string>?. Then I check if selectedItem has a value other than null. This approach should be applicable to whatever type your selected item actually is.
Don't complicate things for no reason. Using SelectedValue property you can easily get a selected ComboBox value like this: YourComboBoxName.SelectedValue.ToString().
Behind the scene the SelectedValue property is defined as: SelectedValue{get; set;} this means you can use it to get or set the value of a ComboBox.
Using SelectedItem is not an efficient way to get a ComboBox value since it requires a lot of ramifications.
You can check SelectedIndex or SelectedValue or SelectedItem property in the SelectionChanged event of the Combobox control.
From SelectionChanged event of a combobox you can get the selected item text as follow:
private void myComboBox_SelectionChanged (object sender, SelectionChangedEventArgs e)
{
ComboBoxItem comboBoxItem = (ComboBoxItem) e.AddedItems[0];
string selectedItemText = comboBoxItem.Content.ToString();
}
clean and easy - TextChanged
private void ComboBox1_TextChanged(object sender, EventArgs e)
{
MessageBox.Show(ComboBox1.Text);
}
Following works for me to get current selection of ComboBox (c# / .net6):
private void comboBox_SelectionChanged(object sender, SelectionChangedEventArgs e) {
string? text = ((ComboBoxItem)(sender as ComboBox).SelectedItem).Content as string;
if(text != null){
...
}
}
This should work for you ...
int myInt= ((data)(((object[])(e.AddedItems))[0])).kid;
I solved this by using the DropDownClosed event because this fires slightly after the value is changed.
I am playing with a Silverlight control that has a TextBox and Button. When I click the button (which calls SelectText below), I want to select all the text in the textbox.
Here's my code:
private void SelectText()
{
TextBox tb = this.txtFirstName;
tb.SelectionStart = 0;
tb.SelectionLength = 3;
// tb.Select(0, this.txtFirstName.Text.Trim().Length - 1);
// tb.SelectAll();
// tb.Text = String.Empty;
}
The commented code is what I tried already, but neither is working.
Anyone have suggestions on what I'm doing wrong?
You might need to give focus to the textbox to see the actual selection happening (either before or after selecting, it might not matter but you'll have to try):
private void SelectText()
{
TextBox tb = this.txtFirstName;
tb.SelectionStart = 0;
tb.SelectionLength = 3;
// tb.Select(0, this.txtFirstName.Text.Trim().Length - 1);
// tb.SelectAll();
// tb.Text = String.Empty;
tb.Focus();
}
SelectAll() works -- I've used it more than once. Is something manipulating the text box after this method happens?
This does the trick for the entire User Control.
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
}
protected override void OnGotFocus(RoutedEventArgs e)
{
TextBox tb = e.OriginalSource as TextBox;
if (tb != null)
tb.SelectAll();
base.OnGotFocus(e);
}
}
The focus solution worked for me, but sometimes I get this ExecutionEngineException during the SelectAll() and it's totally bogus! Even a try...catch won't stop it and there's no more details about the error.