2011-10-07 96 views
1

我需要动态修改一些数据绑定。所以我计划在控制权初始化期间/之后执行操作。System.Windows.Controls.Control without OnLoad方法

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

派生

所以我的问题是:何时以及如何应我对这个控件的绑定进行修改?什么方法重写,或订阅什么事件?

+0

你能描述你想达到什么吗?所以我们可以通过其他方式为您提供建议顺便说一句,你可以处理'Loaded'事件。 –

+0

我是我自己的转换器的子类,显示在组合框中显示的枚举。我的转换器对象需要一些外部处理(如构造参数),并不是一个直接转换器,不能简单地在纯XAML中传递它,更重要的是我必须使用的XAML文件已经是2000行(而且这个是邪恶的)。所以我会在我的Control后面的代码中处理绑定转换器。问题是关于如何/何时可以将绑定设置为控件。 –

回答

3

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

+0

WPF控件...我应该重写什么其他方法或事件订阅呢? –

+0

查看WPF的OnInitialized()。 – roken

+0

就是这样。 http://msdn.microsoft.com/en-us/library/system.windows。frameworkelement.oninitialized.aspx –

1

您确定您从System.Web.UI.Control派生而不是从System.Windows.Forms.Control派生吗?

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

+0

确实它是从System.Windows.Controls.Control派生的......但在我的情况下,我不知道如何在控制之后在它被初始化后进行交互,如果没有入口点如OnLoad覆盖 –

1

System.Windows.Controls.Control不提供OnLoad方法,请参阅基于您的评论MSDN

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型所定义的所有的属性和它们结合显式执行。