问题
I have a WPF ComboBox that binds to a set of data. I do not have permissions to modify the control directly, nor can I change the data.
I'm returned 1 item in my ComboBox, but there are actually 2 rows; the blank row and my expected value. Both appear to have an index value of 0. I don't want to see this blank row, just my expected data in the ComboBox auto-selected. I have looked through everyone's related posts in here, but none of the solutions have worked for my case. I have been programming for a long time, but still fairly new to WPF. Thanks for the help.
XAML
<MyComboBox Name="myTemplate5" MyLookup="Lookup" MyFilter="att_idn=-37" MyData="Detail" MyName="comp_tmpl_idn_srt" ModCde="31" MyEmptyValue="0" ToolTip="Have a nice day" Margin="0,2.5,30,2.5" MinWidth="120" Grid.Column="1" SelectionChanged="myTemplate5_SelectionChanged" />
C#
private void myTemplate1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
MyComboBox work = sender as MyComboBox;
if (work != null && work.HasSelectionChanged(e))
{
int compTmplId = int.Parse(work.SelectedValue.ToString());
if (!_wpfIsDumb && !ChangeComponent(compTmplId))
{
_wpfIsDumb = true;
work.SelectedItem = e.RemovedItems[0];
_wpfIsDumb = false;
}
}
}
public bool HasSelectionChanged(SelectionChangedEventArgs e)
{
if (e.RemovedItems.Count > 0 && e.AddedItems.Count > 0)
return true;
else
return false;
}
回答1:
You can achieved this by setting the SelectedIndex to 0.
XAML:
<ComboBox Name="myCB"
SelectedIndex="0"
MaxWidth="200" MaxHeight="25" />
Code-behind:
namespace nsComboBox
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
myCB.Items.Add("Item 1");
myCB.Items.Add("Item 2");
myCB.Items.Add("Item 3");
myCB.SelectedIndex = 0;
}
}
}
回答2:
I found the solution. The selected index did not work. The problem was with the data. I was getting a NULL value passed to the box. Once I stripped out the NULL return from SQL, then it worked as expected.
来源:https://stackoverflow.com/questions/11442867/wpf-combobox-bad-blank-value