今天做数据验证控件时遇到了个问题,自定义集合控件中的集合项的属性无法进行数据绑定,先列一下关键部分的代码:
验证控件类定义:
public class Validator : Control { public static readonly DependencyProperty ItemsProperty = DependencyProperty.Register( "Items", typeof(ValidatorItemCollection), typeof(Validator), new PropertyMetadata(null)); public ValidatorItemCollection Items { get { return (ValidatorItemCollection)base.GetValue(ItemsProperty); } set { base.SetValue(ItemsProperty, value); } } ……此处略去很多字 }
验证规则集合类定义:
public class ValidatorItemCollection : ObservableCollection<ValidatorItem> { }
验证规则类定义:
public class ValidatorItem : FrameworkElement { public bool IsRequired { get; set; } public static readonly DependencyProperty ValidateSenderProperty = DependencyProperty.Register( "ValidateSender", typeof(string), typeof(ValidatorItem), new PropertyMetadata(string.Empty)); public string ValidateSender { get { return (string)GetValue(ValidatorItem.ValidateSenderProperty); } set { SetValue(ValidateSenderProperty, value); } } }
XAML代码:
<local:Validator x:Name="validator" AutoValidate="{Binding Path=IsEnabled}"> <local:Validator.Items> <local:ValidatorItem x:Name="item1" IsRequired="True"
ValidateSender="{Binding Path=Name, ElementName=textBox1}"></local:ValidatorItem>
</local:Validator.Items>
</local:Validator>
在上述XAML中实例化的ValidatorItem的ValidateSender属性楞是不能成功Binding,但是如果在<local:Validator外部实例化,则Binding是成功的。到处找
有关Binding、ObservableCollection的资料,继承的基类也换来换去,还通过反编译的手段找了DomainDataSource类的相关定义来对照,依然不能解决问题。后来
直接在C#代码里绑定,无意中发现item1居然为null,料想原来是visual tree出了问题:定义的ValidatorItem根本没有加载到控件树中,虽然使用Validator.Items
是可以成功访问到的。
于是乎,到处找关于FindName方法的资料,了解到WPF中需要通过RegisterName来注册NameScope,可是silverlight里根本没有类似方法。
最终,在这个帖子里找到了解决办法:http://stackoverflow.com/questions/4571577/silverlight-usercontrol-child-controls-and-findname
这是给出的回答:
It may be difficult to do at this point but the best course of action would probably be to derive your control from ItemsControl instead of UserControl. Then you wouldn't have the problem with name scopes.
I suppose as a workaround you could do a dive into the control with VisualTreeHelper to manually set the tbTest field
后来将Validator类改为继承自ItemsControl,再把Items属性、ItemsProperty干掉,终于Binding成功了。不过这种方法似乎也不是太好,如果我的Validator类中需要定义好几个集合属性咋办?