【发布时间】:2020-02-26 23:24:00
【问题描述】:
我有一个已经包含默认值的组合框,我想为组合框分配一个值,以便在运行时,分配的值显示为选中状态。
这是组合框
<ComboBox x:Name="MyComboBox" VerticalAlignment="Center" Width="50" Padding="1" Height="23">
<ComboBoxItem IsSelected="True">A</ComboBoxItem>
<ComboBoxItem>B</ComboBoxItem>
<ComboBoxItem>C</ComboBoxItem>
<ComboBoxItem>D</ComboBoxItem>
<ComboBoxItem>E</ComboBoxItem>
<ComboBoxItem>F</ComboBoxItem>
<ComboBoxItem>G</ComboBoxItem>
<ComboBoxItem>H</ComboBoxItem>
<ComboBoxItem>I</ComboBoxItem>
<ComboBoxItem>K</ComboBoxItem>
<ComboBoxItem>L</ComboBoxItem>
<ComboBoxItem>M</ComboBoxItem>
<ComboBoxItem>N</ComboBoxItem>
</ComboBox>
我分配的值将是默认值之一。因此,我不想添加新项目。只是为了显示我指定为选中的项目。
这是我尝试但没有成功的方法:
//I get a value from reading a datareader
string MyValue = datareader.GetString(0);
// I assign the value to the combobox:
MyComboBox.SelectedItem = MyValue; //Attempt 1
MyComboBox.SelectedValue = MyValue; //Attempt 2
MyComboBox.Text= MyValue; //Attempt 3
MyComboBox.SelectedIndex = MyValue; //Attempt 4. Throws an error as MyValue is a string
感谢您的帮助!
【问题讨论】:
-
这是一个 WPF 应用程序吗?
-
是的。添加标签