how to get combobox selected item to string

how do i get my combobox selected item that are populated from a itemsource to a string so i can use it in my post that are in another void as with string bolts = comboBox_Copy.Text; or string bolts = comboBox.Copy.SelectedItem; gives null

     private void boltPatterns()
    {
        {
            try
            {
                string Url = URL_Domain + "resources/bolt-pattern";
                Uri serviceUri = new Uri(Url);
                using (WebClient webClient = new WebClient())
                {
                    webClient.Encoding = Encoding.UTF8;
                    string api = webClient.DownloadString(serviceUri);

                    List<boltPatterns> values =  JsonConvert.DeserializeObject<List<boltPatterns>>(api);
                    comboBox_Copy.ItemsSource= values;
                }
            }

XAML

 <ComboBox x:Name="comboBox_Copy" DisplayMemberPath="BoltPattern" SelectedItem="{Binding BoltPattern}">

Upvotes: 1

Views: 784

Answers (3)

ZoolWay
ZoolWay

Reputation: 5505

You are using bindings (which is a good thing), so you do not need (and in MVVM mostly should not) access the combobox itself.

If you would like to use MVVM, set on your top-level component this DataContext to enable binding to code-behind properties:

DataContext="{Binding RelativeSource={RelativeSource Self}}"

Then in the code-behind class create a property SelectedBoltPattern of type boltPatterns (thats how you spelled it in your example). Adopt the SelectedItem binding in your XAML to

SelectedItem="{Binding SelectedBoltPattern}"

Note that this matches the property name.

In code-behind you can access the currently selected item with this.SelectedBoltPattern.

Once you get used to binding you might want to do even the easiest applications with a simple MVVM framework like Caliburn.Micro e.g. Those make these things very easy.

Upvotes: 1

Faizan Nasir
Faizan Nasir

Reputation: 9

string bolts = comboBox.Text.ToString();

Upvotes: 0

Daniel Loudon
Daniel Loudon

Reputation: 799

string bolts = comboBox.SelectedItem.ToString();

Upvotes: 2

Related Questions