【问题标题】:System.Windows.Controls.Control without OnLoad methodSystem.Windows.Controls.Control 没有 OnLoad 方法
【发布时间】:2011-10-07 12:19:20
【问题描述】:

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

但是尽管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

所以我的问题变成了:我应该何时以及如何对此控件的绑定进行修改?重写什么方法,或者订阅什么事件?

【问题讨论】:

  • 您能描述一下您想要实现的目标吗?所以我们可以用另一种方式为您提供建议。顺便说一句,您可以处理 Loaded 事件。
  • 我将我自己的转换器子类化为组合框中显示的枚举。我的转换器对象需要一些外部处理(如构造参数)并且不是直前转换器,不能简单地在纯 XAML 中传递它,更何况我必须使用的 XAML 文件已经是 2000 行(而且这个是邪恶的)。所以我会在我的 Control 后面的代码中处理这个绑定转换器。问题是我如何/何时可以将绑定设置为控件。

标签: c# .net wpf controls overriding


【解决方案1】:

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

【讨论】:

【解决方案2】:

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

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

【讨论】:

  • 确实它是从 System.Windows.Controls.Control...作为 OnLoad 覆盖
【解决方案3】:

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

【讨论】:

    【解决方案4】:

    根据您的评论,我建议您创建 ViewBinder,它可以轻松设置转换器并最大限度地提高透明度。

    MIX10 和 Caliburn 上查看 Rob Eisenberg 的演讲或可从该页面下载的演讲代码。

    框架根据约定定位 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 类型中定义的所有属性并绑定它们。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-01-06
      • 2014-12-01
      • 2012-06-13
      • 1970-01-01
      • 1970-01-01
      • 2013-04-20
      • 2016-12-10
      相关资源
      最近更新 更多