没有OnLoad方法的System.Windows.Controls.Control

时间:2011-10-07 12:19:20

标签: c# .net wpf controls override

我需要动态修改一些数据绑定。所以我计划在其父级控件初始化期间/之后执行操作。

但是尽管the msdn page on Control.OnLoad Method,我的班级拒绝编译:

  

错误810'Views.Test.OnLoad(System.EventArgs)':找不到合适的方法来覆盖

我的代码:

class Test : Control 
{
    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);
        if (true)
        {
            System.Diagnostics.Debug.Assert(false);            
        }
    }
}

对我做错了什么的想法?

编辑: @Roken注意到我与System.Web.UI.Control不匹配,因为我的类派生自System.Windows.Controls.Control

所以我的问题变成:何时以及如何对此控件的绑定执行修改?要覆盖什么方法,或要订阅什么事件?

4 个答案:

答案 0 :(得分:3)

这是Windows窗体控件还是Web控件?您提供的链接用于Web控件; WinForms控件不包含OnLoad()。 OnCreateControl()可能对WinForms有用,对WPF也有用OnInitialized()。

答案 1 :(得分:1)

您确定是源自System.Web.UI.Control而不是来自System.Windows.Forms.Control吗?

System.Windows.Forms.Control未提供虚拟OnLoad方法。

答案 2 :(得分:1)

System.Windows.Controls.Control不提供OnLoad方法,请参阅MSDN

答案 3 :(得分:1)

根据您的评论,我建议您创建ViewBinder,只需稍加努力并最大限度地提高透明度即可设置转换器。

查看Rob Eisenberg在MIX10和Caliburn的讲话,或者从该页面下载的演讲代码。

根据约定,框架定位UI元素并将其与同名属性匹配。并自动创建和调整绑定:

private static void BindProperties(FrameworkElement view, IEnumerable<PropertyInfo> properties)
{
  foreach (var property in properties)
  {
    var foundControl = view.FindName(property.Name) as DependencyObject;
    if(foundControl == null) // find the element
      continue;

    DependencyProperty boundProperty;
    if(!_boundProperties.TryGetValue(foundControl.GetType(), out boundProperty))
      continue;
    if(((FrameworkElement)foundControl).GetBindingExpression(boundProperty) != null) // already bound
      continue;

    var binding = new Binding(property.Name) // create the binding
    {
      Mode = property.CanWrite ? BindingMode.TwoWay : BindingMode.OneWay,
      ValidatesOnDataErrors = Attribute.GetCustomAttributes(property, typeof(ValidationAttribute), true).Any()
    };

    if (boundProperty == UIElement.VisibilityProperty && typeof(bool).IsAssignableFrom(property.PropertyType))
      binding.Converter = _booleanToVisibilityConverter;

    BindingOperations.SetBinding(foundControl, boundProperty, binding);
  }
}

绑定在public static void Bind(object viewModel, DependencyObject view)方法中显式完成,该方法采用viewModel类型中定义的所有属性并绑定它们。