Why SelectedItem property does not work with ComboBoxItem strings?
I want to select combobox items by their string value but I have a problem. A simple test:
<ComboBox SelectedItem="text1" ItemsSource="{Binding MyListOfStrings}">
</ComboBox>
MyListOfS开发者_JAVA百科trings has list with strings "text1", "text2", "text3". This way it works fine - the text1 gets selected.
But the following way does not work:
<ComboBox SelectedItem="text1">
<ComboBoxItem>text1</ComboBoxItem>
<ComboBoxItem>text2</ComboBoxItem>
<ComboBoxItem>text3</ComboBoxItem>
</ComboBox>
What is wrong with it? Why WPF cannot find text1 if I define items in XAML?
P.S. Actually SelectedItem uses data binding, I just simplified the example.
you can set the selected item with Selector.IsSelected="True"
for that ComboItem
<ComboBox>
<ComboBoxItem Selector.IsSelected="True">text1</ComboBoxItem>
<ComboBoxItem>text2</ComboBoxItem>
<ComboBoxItem>text3</ComboBoxItem>
</ComboBox>
Edit :
if you are using Binding, creat a ComboBoxItem property
public ComboBoxItem MyProperty
{
get
{
ComboBoxItem ci = new ComboBoxItem();
ci.Content = "text1";
return ci;
}
}
and Bind
SelectedItem="{Binding Path=MyProperty}"
I guess it doesn't work because ComboBoxItem is not a string, and there is no converter from string to ComboBoxItem. But ComboBoxItem offers a "IsSelected" property that you could use.
精彩评论