WPF的SelectedItem与DataTemplate的可编

WPF的SelectedItem与DataTemplate的可编

本文介绍了WPF的SelectedItem与DataTemplate的可编辑组合框的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在WPF ComboBox 遇到以下问题:

I’m having the following issue with WPF ComboBox:

<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();
}



我打开窗口并获取 ComboBox

I open the window and get ComboBox, bounded to my data model, I select some item (e.g. 1), all is dandy.

我将数据上下文更改为一个新的数据模型 - 我选择了一个项目(例如1),所有都是dandy。所选项目是(令我惊讶的)1 ...我不期望任何选定的项目...

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...

我怀疑它与组合有关

我发现一个工作:调用 UpdateLayout()

I found a work around: call UpdateLayout() on the ContentControl bounded to the DataContext, but it’s ugly.

是WPF错误吗?这是我的错吗?

Is that WPF bug? Is it all my fault?

请帮助

推荐答案

我们向,它似乎是一个微软的错误。
有一个解决方法,我发现,丑陋,但它的工作。这是修改后的代码:

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();
    }


$ b需要解决这个问题。

Note that both setting the DataContext to null and calling UpdateLayout() on DataContextChanged are needed to solve this issue.

这篇关于WPF的SelectedItem与DataTemplate的可编辑组合框的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 22:38