如何根据自定义类通过代码设置WPF Combobox SelectedValue?

时间:2012-01-18 19:33:55

标签: c# wpf

我需要通过代码选择WPF Combobox下的自定义项目。例如:“西班牙语”

 UILanguages languages = new UILanguages();                
                languages.Add(
                        new UILanguage
                        {
                            Culture = "en",
                            SpecCulture = "en-US",
                            EnglishName = "English"
                        });

                languages.Add(
                    new UILanguage
                    {
                        Culture = "es",
                        SpecCulture = "es-ES",
                        EnglishName = "Spanish"
                    });

                CollectionViewSource cvs = new CollectionViewSource
                {
                    Source = languages
                };

                cmbLanguages.SetBinding(ItemsControl.ItemsSourceProperty, new Binding { Source = cvs });

标记

  <ComboBox Grid.Column="1" Height="23" HorizontalAlignment="Left" Margin="0,1,0,0" 
              Name="cmbLanguages" VerticalAlignment="Top" Width="207"
           ItemsSource="{Binding Source={StaticResource UILanguagesViewSource}}" 
              />

请注意

但是这个 Set SelectedItem of WPF ComboBox 还有这个 WPF combobox binding from code behind 没有任何帮助。

有任何线索吗?

谢谢!

2 个答案:

答案 0 :(得分:1)

您需要将SelectedValue属性设置为您的语言的特定实例。这可以通过以下方式完成:

// Get first element with proper name from the bound source
cmdLanguages.SelectedValue = languages.FirstOrDefault(l => l.EnglishName == "Spanish");

答案 1 :(得分:1)

或者除了Reed的asnwer你可以(伪代码),首先绑定到一个属性

<ComboBox ... SelectedItem="{Binding Path=Selected}" />

UILanguage中有一个布尔属性Selected

并从后面的代码做,像这样

UILanguage lang = languages.FirstOrDefault(l => l.EnglishName == "MyLanguage");
lang.Selected = true;

//更新绑定

在这种情况下,肯定会有更多代码,但纯WPF编码。