问题
I’m having the following issue with WPF ComboBox
:
XAML:
<Window.Resources>
<ResourceDictionary>
<DataTemplate DataType="{x:Type this:Data}">
<ComboBox IsTextSearchEnabled="False" IsEditable="True"
Text="{Binding Value}" ItemsSource="{Binding Menu}"/>
</DataTemplate>
</ResourceDictionary>
</Window.Resources>
<StackPanel>
<ContentControl Content="{Binding}"/>
<Button Click="ChangeData_Click">Change Data</Button>
</StackPanel>
Code behind:
public Window1()
{
InitializeComponent();
DataContext = new Data();
}
void ChangeData_Click(object sender, RoutedEventArgs e)
{
DataContext = new Data();
}
I open the window and get ComboBox
, bounded to my data model, I select some item (e.g. 1), all is dandy.
I change the data context to a new data model – the selected item is (to my surprise) 1... Where I don't expect any selected item...
I suspect it has something to do with the combo box which search disabled and editable, but I’m not sure what was the problem.
I found a work around: call UpdateLayout()
on the ContentControl
bounded to the DataContext
, but it’s ugly.
Is that WPF bug? Is it all my fault?
Please Help
回答1:
I've submitted the same question to MSDN WPF Forum and it seems like a Microsoft bug. There's a workaround I found, ugly, but it's working. Here's the modified code behind:
public Window1()
{
InitializeComponent();
DataContext = new Data();
DataContextChanged += delegate { contentControl.UpdateLayout(); };
}
void ChangeData_Click(object sender, RoutedEventArgs e)
{
DataContext = null;
DataContext = new Data();
}
Note that both setting the DataContext to null and calling UpdateLayout() on DataContextChanged are needed to solve this issue.
来源:https://stackoverflow.com/questions/1389040/problem-with-selecteditem-of-wpf-editable-combobox-with-datatemplate