如何将lostfocus事件处理程序添加到动态创建的组合框的文本框中?

时间:2013-05-13 16:37:54

标签: c# wpf combobox

Combobox不可编辑但我尝试过:

TextBox TxtBox = (TextBox)myCombo.Template.FindName("PART_EditableTextBox", myCombo);

但它变为空。

我尝试将其添加到Windows xaml:

   <Style TargetType="{x:Type ComboBox}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type TextBox}">
                    <Border x:Name="PART_EditableTextBox" Focusable="True" Background="{TemplateBinding Background}" />
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

但是发生了System.Windows.Markup.XamlParseException:

Set property 'System.Windows.ResourceDictionary.DeferrableContent' threw an exception.

以下是我用来创建Combobox并在网格中设置它的位置的代码:

public static System.Windows.Controls.ComboBox createNewComboBox(String newComboBoxName, SelectionChangedEventHandler selectionChangedEventHandler,RoutedEventHandler lostFocusEventHandler)
    {
        System.Windows.Controls.ComboBox newComboBox = new System.Windows.Controls.ComboBox();
        newComboBox.Name = newComboBoxName;
        if (selectionChangedEventHandler != null) newComboBox.SelectionChanged += selectionChangedEventHandler;
        if (lostFocusEventHandler != null) newComboBox.LostFocus += lostFocusEventHandler;
        return newComboBox;
    }

    public static void setNewControlLocation(System.Windows.Controls.Control control, Int32 rowIndex, Int32 columnIndex, Grid parent)
    {
        Grid.SetRow(control, rowIndex);
        Grid.SetColumn(control, columnIndex);
        parent.Children.Add(control);
    }

这会将lostfocus添加到组合框而不是组合框的文本框中。

用户选择并输入数据有一行。用户可以通过单击加号按钮或屏幕左侧或使用F5键添加更多行。该行包含几个控件,其中一个是组合框。组合框下拉产品名称列表,如果选择了某些产品,则需要显示消息框。如果我将代码放在SelectionChanged事件处理程序中并且用户正在搜索组合框,则消息框将在每次传递其中一个需要它的产品时显示。如果我将消息框的代码放在combobox的lostfocus事件处理程序中,当你单击组合框的文本框并关闭窗口时它会触发。所以我需要找到一种方法将事件处理程序附加到组合框的文本框中。

如果还有另外一种方法,请告诉我。

screen shot

0 个答案:

没有答案