【问题标题】:Handling Events For Controls Added At Run Time处理运行时添加的控件的事件
【发布时间】:2018-09-27 06:35:20
【问题描述】:

我在运行时在 WPF 应用程序中添加控件,这些都是不同类型的控件,因此作为 UIElement 传递。然后我得到控制的type 并可以使用SetValue 设置属性。因为我有很多控件类型来实现我现在尝试做的是向每个控件添加一个事件,但似乎只能使用Addhandler 来执行此操作,这需要为每个控件添加大量额外代码,如下所示。我正在寻找一种解决方案,允许我将错误处理程序添加到 UIElement,而无需使用 Cast 进行事先转换,我不确定这是否可行?

 Select Case Control.GetType()
                Case GetType(ExtendedTextBox)
                    Dim newControl As ExtendedTextBox = TryCast(Control, ExtendedTextBox)
                    'Dim newCtl As UIElement = TryCast(Control, ExtendedTextBox)
                    If newControl IsNot Nothing Then
                        newControl.SetValue(ExtendedTextBox.HorizontalAlignmentProperty, HorizontalAlignment.Left)
                        newControl.SetValue(ExtendedControlProperties.HighlightTextOnFocusProperty, True)
                        newControl.SetValue(ExtendedControlProperties.MandatoryProperty, True)
                        AddHandler newControl.HasErrors, AddressOf UpdateErrorStatus
                    End If

【问题讨论】:

  • 你应该看看 DataTemplate。没有必要像你那样做。见wpftutorial.net/datatemplates.html
  • 谢谢,但我不确定 DataTemplate 在这种情况下如何工作,因为我在运行时添加了多种控件类型,例如文本块、组合框、按钮等,所有这些我都需要HasErrors 事件被处理。
  • 什么是ExtendedTextBox 及其HasErrors 事件?如果它是其他控件也继承自基类的一部分,则可以将其强制转换为那些控件。

标签: wpf vb.net controls


【解决方案1】:

我错误地将验证前缀为“客户”。在继承控制中导致问题的原因是,一旦删除它就可以按预期工作。

【讨论】:

    猜你喜欢
    • 2010-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多