I have a combobox in a WPF XAML window. I want to have an IF statement in my .cs where I can then assign a method to it when the user has that item selected.
Here is the XAML bit:
<ComboBox x:Name="comboBoxThickness" HorizontalAlignment="Left"
Margin="469,380,0,0" VerticalAlignment="Top" Width="155" IsEditable="True"
MaxWidth="150" Text="Select Plate Thickness">
<ComboBoxItem x:Name="Combo8mm" Content="8mm" />
<ComboBoxItem x:Name="Combo12_5mm" Content="12.5mm" />
</ComboBox>
Here is the .cs part (with an attempt made):
private void WeightCal()
{
if (Combo8mm.Selected){
}
}
Based on your question, I have added code snippet assuming that you wanted to do something on combo-box selected changed event.
Case 1 :-
I have done little modification to your xaml and code-behind.
Added a SelectedChanged event to combobox as below.
<ComboBox x:Name="comboBoxThickness" HorizontalAlignment="Left" VerticalAlignment="Top" Width="155" IsEditable="True"
MaxWidth="150" Text="Select Plate Thickness" SelectionChanged="comboBoxThickness_SelectionChanged">
<ComboBoxItem x:Name="Combo8mm" Content="8mm" />
<ComboBoxItem x:Name="Combo12_5mm" Content="12.5mm" />
</ComboBox>
Then in the code behind in the event handler, you can check which Combobox item is selected like below,
private void comboBoxThickness_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var selectedItem = comboBoxThickness.SelectedItem as ComboBoxItem;
if(selectedItem.Content.ToString() == "8mm")
{
// Write your logic here
}
}
You can multiple if..else conditions to check and do necessary actions in each if condition as per your requirements.
Note:- Even though the approach you have followed was not recommended. Always rely on MVVM which helps you in long run.
And in the above code I am just trying to compare the selected combo-box item content with string. Assuming it is always a string in your case. You have to check and test the code in your project.
Case 2:-
In case if you want to get the selected item in some method, you can directly use this below statement instead of checking that each combo-box item is selected or not which you have written in your code.
var selectedItem = comboBoxThickness.SelectedItem as ComboBoxItem;
if(selectedItem.Content.ToString() == "8mm")
{
// Write your logic here
}
If there is something else that you are looking for, then let us know.
Related
I try to use a CheckComboBox control from the Xceed library.
When I select an item, the control displays system.windows.controls.comboxitem:"value" instead of just value
Is there a way to display only the value of the selected item without its type?
<xctk:CheckComboBox>
<ComboBoxItem Content="SA" />
<ComboBoxItem Content="NA" />
</xctk:CheckComboBox>
In this particular case it can be solved by adding the DisplayMemberPath="Content"
<xctk:CheckComboBox DisplayMemberPath="Content">
<ComboBoxItem Content="SA"/>
<ComboBoxItem Content="NA"/>
</xctk:CheckComboBox>
But whether it is a designed feature or just a serendipitous behaviour, I am not sure.
So overall it would be better in the future to read on WPF binding, and use datasources and bindings to make the code similar to what is on the documentation page.
<xctk:CheckComboBox
DisplayMemberPath="Color"
ValueMemberPath="Level"
SelectedValue="{Binding SelectedValue}"
SelectedItems="{Binding SelectedItems}" />
I have a list box
<Label Content="Report" HorizontalAlignment="Left" Height="47" Margin="36,75,0,0" VerticalAlignment="Top" Width="63"/>
<ListBox x:Name="ListBox1" HorizontalAlignment="Left" Height="121" Margin="84,75,0,0" VerticalAlignment="Top" Width="102" SelectionChanged="ListBox_SelectionChanged" SelectedIndex="-1">
<ListBox Height="100" Width="100" SelectionChanged="ListBox_SelectionChanged_1">
<ListBoxItem x:Name="ListBoxFAT" Content="FAT"/>
<ListBoxItem x:Name="ListBoxNUMI" Content="NUMI"/>
<ListBoxItem x:Name="ListBoxSSID" Content="SSID"/>
<ListBoxItem x:Name="ListBoxFact" Content="FACT"/>
</ListBox>
</ListBox>
This was created by dragging the listbox icon from the tool bar. I added items and their values.
Now I am trying to just get the text value of the selected item.
private void ListBox_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
{
string text = (string)ListBox1.SelectedValue;
MessageBox.Show(text);
I have also tried SelectedItem
string text = (string)ListBox1.SelectedItem;
But the message box is always blank.
This should be simple, but I have been working on it for hours, and trying every suggestion or answer on stackoverflow. Most suggestions do not even compile. For example:
string selected = listBox1.GetItemText(listBox1.SelectedValue);
Will not compile. GetItemText is not found. I am using Visual Studio 17. "'ListBox does not contain a definition for 'GetItemText'..."
Any thoughts? Please advise. Thanks.
Thanks for the comment, Charles. I did that.
Playing further, now I get
System.InvalidCastException: 'Unable to cast object of type 'System.Windows.Controls.ListBoxItem' to type 'System.String'.'
string text = (string)ListBox1.SelectedItem;
As indicated by Charles May, your XAML shows that your ListBox is within another ListBox, which is why you're getting errors being raised..
The event being called "ListBox_SelectionChanged_1" is bound to the ListBox object inside ListBox1, which is unnamed.
I believe that the behaviour you are looking for would be fixed like this:
XAML:
<Label Content="Report" HorizontalAlignment="Left" Height="47" Margin="36,75,0,0" VerticalAlignment="Top" Width="63"/>
<ListBox x:Name="ListBox1" HorizontalAlignment="Left" Height="121" Margin="84,75,0,0" VerticalAlignment="Top" Width="102" SelectionChanged="ListBox_SelectionChanged" SelectedIndex="-1">
<ListBoxItem x:Name="ListBoxFAT" Content="FAT"/>
<ListBoxItem x:Name="ListBoxNUMI" Content="NUMI"/>
<ListBoxItem x:Name="ListBoxSSID" Content="SSID"/>
<ListBoxItem x:Name="ListBoxFact" Content="FACT"/>
</ListBox>
Code Behind:
private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
string text = ((sender as ListBox)?.SelectedItem as ListBoxItem)?.Content.ToString();
MessageBox.Show(text);
}
Or at least something close to this solution.
In the markup, SelectedIndex is set to -1 which means there is no selection. In this case, SelectedValue and SelectedItem both return null. You can solve this either by setting SelectedIndex to a value between 0 and 3 or by preparing your code to cope with a null value in SelectedValue and SelectedItem, e.g.
string text = (ListBox1.SelectedItem as ListBoxItem)?.Content?.ToString();
This won't raise an error so that the user can select an item afterwards. With a selection, the text should be displayed as expected.
this is my combo box(xaml code) :
<ComboBox SelectionChanged="ComboBox1_SelectionChanged" Name="ComboBox1" SelectedIndex="1" FontWeight="Bold" FontSize="15" Canvas.Left="133" Canvas.Top="240" Width="135" Height="24">
<ComboBoxItem Foreground="Red" Name="Red">Red</ComboBoxItem>
<ComboBoxItem Foreground="Blue" Name="Blue">Blue</ComboBoxItem>
<ComboBoxItem Foreground="Yellow" Name="Yellow">Yellow</ComboBoxItem>
<ComboBoxItem Foreground="Pink" Name="Pink">Pink</ComboBoxItem>
<ComboBoxItem Foreground="Green" Name="Green">Green</ComboBoxItem>
</ComboBox>
and this is my c# code :
private void ComboBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (ComboBox1.Text != "")
{
var converter = new System.Windows.Media.BrushConverter();
var brush = (Brush)converter.ConvertFromString(ComboBox1.Text);
rect.Fill = brush;
}
}
I have a rectangle that I want to fill in the color chosen in the combo box, I also want the default color on the combo box to be blue, both however don't really work for me. The text on the combo box is in fact blue by default but I think the item itself isn't selected because it doesn't recognize it and tells me my combo box string is empty by default. Furthermore, my rectangle's colors change in a delay, if I choose red first-nothing is going to happen and then if I choose green second it's gonna show red and it keeps going in that delay.
Does anyone know why? and how to solve it? I would be extremely grateful.
At the end I managed to solve this by changing the SelectionChanged event with the DropDownClosed event.
I have the following ComboBox:
<ComboBox x:Name="splitInput_ComboBox" SelectionChanged="spltComboBox_SelectionChanged">
<ComboBoxItem Tag="0" IsSelected="True">None</ComboBoxItem>
<ComboBoxItem Tag="2">2</ComboBoxItem>
<ComboBoxItem Tag="3">3</ComboBoxItem>
</ComboBox>
How can I assign the user selection to an int or double variable in the code behind? Is data binding the only way to accomplish this?
In your spltComboBox_SelectionChanged event handler you can get selected item or selected value using these properties:
SelectedItem
SelectedValue
like:
splitInput_ComboBox.SelectedValue;
Note: I recommend you not to use underscore while naming your controls as you did "splitInput_ComboBox".
I have a ComboBox that needs to depend on the value of another ComboBox. This part already works, with the dependent ComboBox refreshing when a new value is chosen in the independent ComboBox:
<!-- Independent -->
<ComboBox Height="23" HorizontalAlignment="Left" Grid.Row="2" Grid.Column="2"
x:Name="cbo_product" VerticalAlignment="Center" Width="120"
ItemsSource="{Binding Source={StaticResource productsXml}}"
DisplayMemberPath="#name" SelectedValuePath="#name"
SelectionChanged="cbo_product_SelectionChanged"
SelectedValue="{Binding Path=Product}" />
<!-- Dependent -->
<ComboBox Height="23" HorizontalAlignment="Left" Grid.Row="3" Grid.Column="2"
x:Name="cbo_component" VerticalAlignment="Center" Width="201"
DataContext="{Binding SelectedItem, ElementName=cbo_product}"
ItemsSource="{Binding XPath=Components/Component}"
DisplayMemberPath="#name" SelectedValuePath="#name"
SelectedValue="{Binding Path=Component}"
SelectionChanged="cbo_component_SelectionChanged" />
In the C# class behind this, I have:
public MyUserControlConstructor()
{
MyViewModelInstance= new MyViewModel();
DataContext = MyViewModelInstance;
}
And in MyViewModel, I have:
public string Component
{
get { return _component; }
set
{
if (value == _component)
{
return;
}
_component = value;
onPropertyChanged(PropertyNames.Component);
}
}
private void onPropertyChanged(PropertyNames fieldName)
{
if (null == PropertyChanged)
{
return;
}
string propertyName = Enum.GetName(typeof(PropertyNames), fieldName);
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
When I change the dependent ComboBox (Component), it shows up with the new value in my app, of course. However, when I hit a button that causes the value of the Component property to be displayed, it is always the initial value, and not the value I just chose in the ComboBox. I think there must be an error in my XAML. For the C#, I tried to follow a combination of this and this guide. How do I tie my dependent ComboBox to XML values nested in the SelectedItem of the independent ComboBox, but still update the Component property in my class?
Edit: my suspicion is that things are wonky because I set the DataContext for the dependent ComboBox in two places: first in the constructor in C#, to my view model, and second in the XAML, to DataContext="{Binding SelectedItem, ElementName=cbo_product}".
Edit: I had been setting initial values in the constructor to my view model class. When I take out the initial value for the Component property, then even after I change the selected value in the dependent ComboBox, I still get no value from the Component property. This pretty much just rehashes what I already knew: the dependent ComboBox is tied to the independent ComboBox (it gets its data from the independent ComboBox, that is), but not to the Component property.
Edit: by request, here's a sample of my XML:
<Products xmlns="">
<Product name="Awesomeness">
<Components>
<Component name="Component of Glory"/>
<Component name="Component of Doom"/>
</Components>
</Product>
</Products>
Edit: I'm guessing a MultiBinding would be of use, after looking at this and this.
Edit: it seems like I should be able to get the dependent ComboBox to work without setting DataContext, just by using ItemsSource:
<ComboBox Height="23" HorizontalAlignment="Left" Grid.Row="3" Grid.Column="2"
x:Name="cbo_component" VerticalAlignment="Center" Width="201"
ItemsSource="{Binding ElementName=cbo_product, Path=SelectedItem,
XPath=Components/Component}"
DisplayMemberPath="#name" SelectedValuePath="#name"
SelectedValue="{Binding Path=Component}"
SelectionChanged="cbo_component_SelectionChanged"/>
However, this doesn't work: the dependent ComboBox is empty, instead of showing all the Component names.
The way I found of getting around this involves setting the ItemsSource in C# instead of XAML, which I would prefer not to do. However, it works, and after a day and a half of banging on this, it's the best I came up with.
In XAML:
<!-- Independent -->
<ComboBox Height="23" HorizontalAlignment="Left" Grid.Row="2" Grid.Column="2"
x:Name="cbo_product" VerticalAlignment="Center" Width="120"
ItemsSource="{Binding Source={StaticResource productsXml}}"
DisplayMemberPath="#name" SelectedValuePath="#name"
SelectionChanged="cbo_product_SelectionChanged"
SelectedItem="{Binding Path=ProductNode}"
SelectedValue="{Binding Path=Product}" />
<!-- Dependent -->
<ComboBox Height="23" HorizontalAlignment="Left" Grid.Row="3" Grid.Column="2"
x:Name="cbo_component" VerticalAlignment="Center" Width="201"
DisplayMemberPath="#name" SelectedValuePath="#name"
SelectedValue="{Binding Path=Component, Mode=TwoWay}"
SelectionChanged="cbo_component_SelectionChanged"/>
In C#, the event handler for when the independent ComboBox changes:
private void cbo_product_SelectionChanged(object sender,
SelectionChangedEventArgs e)
{
// Set ItemsSource of dependent ComboBox
cbo_component.ItemsSource = getChildNodesFromComboBox(
sender as ComboBox, "Components/Component"
);
cbo_component.SelectedIndex = 0;
}
// Helper method to do XPath query and get child nodes from selected value of
// independent ComboBox
private XmlNodeList getChildNodesFromComboBox(ComboBox comboBox,
string xpath)
{
if (null == comboBox)
{
return null;
}
var xml = comboBox.SelectedItem as XmlElement;
if (null == xml)
{
return null;
}
return xml.SelectNodes(xpath);
}
Now the Component property in my view model class, to which my dependent ComboBox is bound in XAML, gets populated with the value selected in the dependent ComboBox because I didn't have to change the DataContext of the dependent ComboBox.