【问题标题】:WPF ContentTemplateSelector doesn't change template in time for ListboxSelectionChangedWPF ContentTemplateSelector 不会及时更改 ListboxSelectionChanged 的​​模板
【发布时间】:2014-05-17 15:39:14
【问题描述】:

我有一个按预期成功更改的 ContentTemplateSelector。它在一个列表框中,其中包含一堆文本块,然后当您在列表框中选择一个项目时,该项目将其模板更改为具有一个文本框(因此可以对其进行编辑)。

我遇到的问题是文本框没有获得焦点。这有点烦人。

所以我一直在尝试为列表框实现一个附加属性,该属性在设置后会将一个事件处理程序附加到 SelectionChanged 事件。从那里,我希望向下钻取,找到文本框并设置它的焦点。

但是,我遇到了一个障碍,TemplateSelector 似乎还没有选择合适的模板(带有文本框的模板)。事实上,Template 是 NULL。这让我相信它已经删除了 TextBlock 模板,并且很快就会选择正确的模板,但只有在整个 SelectionChanged 事件完成之后。

我的问题是,您是否知道一种方法可以强制此 DataTemplate 告诉它是 ContentTemplateSelector 来选择适当的模板,或者是关于如何在 ListboxItem 时选择模板内的此文本框的不同想法获得焦点?

以下是我获取 ContentPresenter 的方法(从选定的 ListboxItem 中):

ContentPresenter cp = FindVisualChild<ContentPresenter>(lbi);

编辑:我在此之后添加了 cp.ApplyTemplate(),但这并没有改变任何东西。

cp.ContentTemplate 此时为空。

【问题讨论】:

    标签: c# wpf templates listbox contenttemplateselector


    【解决方案1】:

    所以我自己想通了,想发布我的答案,以防其他人有类似的问题。

    首先,在我的 TemplateSelector 中,为最后选择的模板添加了一个属性,我可以在代码中访问该属性(称为 SelectedTemplate)。

    然后在列表框选择改变事件的情况下进行如下操作:

     ContentPresenter cp = FindVisualChild<ContentPresenter>(lbi);
     var templateSelector = cp.ContentTemplateSelector;
     cp.ApplyTemplate();
    
     var template = (templateSelector as DegreeLearningItemTemplateSelector)
                                .SelectedTemplate;
     if (template != null)
     {
         var textbox = (TextBox)template.FindName("PART_TextBox", cp);
    
         if (textbox != null)
         {
            FocusManager.SetFocusedElement(lbi, textbox);
            textbox.CaretIndex = textbox.Text.Length;
         }
     }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-14
      • 1970-01-01
      • 2013-04-11
      • 2011-09-08
      • 2012-11-27
      • 1970-01-01
      • 2014-01-26
      • 2012-06-22
      相关资源
      最近更新 更多