我建议你创建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
型所定义的所有的属性和它们结合显式执行。
你能描述你想达到什么吗?所以我们可以通过其他方式为您提供建议顺便说一句,你可以处理'Loaded'事件。 –
我是我自己的转换器的子类,显示在组合框中显示的枚举。我的转换器对象需要一些外部处理(如构造参数),并不是一个直接转换器,不能简单地在纯XAML中传递它,更重要的是我必须使用的XAML文件已经是2000行(而且这个是邪恶的)。所以我会在我的Control后面的代码中处理绑定转换器。问题是关于如何/何时可以将绑定设置为控件。 –