Problem with SelectedItem from WPF Editable ComboBox with DataTemplate

I have the following problem 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 a window and get ComboBox, limited by my data model, I select some element (for example, 1), all this is dandy.

I am changing the data context to a new data model - the selected item (to my surprise) 1 ... Where I do not expect any selected item ...

I suspect this is due to the combo box whose search is disabled and editable, but I'm not sure what the problem is.

I found a job: call UpdateLayout()on ContentControl, limited DataContext, but its ugly.

Is this a WPF error? Is it all my fault?

Please, help

+3
1

MSDN WPF Forum, Microsoft. , , . :

    public Window1()
    {
        InitializeComponent();
        DataContext = new Data();
        DataContextChanged += delegate { contentControl.UpdateLayout(); };
    }

    void ChangeData_Click(object sender, RoutedEventArgs e)
    {
        DataContext = null;
        DataContext = new Data();
    }

, DataContext null UpdateLayout() DataContextChanged.

0

Source: https://habr.com/ru/post/1717058/


All Articles