轉帖|其它|編輯:郝浩|2011-03-07 13:23:16.000|閱讀 575 次
概述:今天做數據驗證控件時遇到了個問題,自定義集合控件中的集合項的屬性無法進行數據綁定,因此本文就SilverLight自定義集合控件中的集合項數據綁定問題與大家一起分享我的經驗,希望對大家有幫助。
# 界面/圖表報表/文檔/IDE等千款熱門軟控件火熱銷售中 >>
今天做數據驗證控件時遇到了個問題,自定義集合控件中的集合項的屬性無法進行數據綁定,先列一下關鍵部分的代碼:
驗證控件類定義:
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>
有關Binding、ObservableCollection的資料,繼承的基類也換來換去,還通過反編譯的手段找了DomainDataSource類的相關定義來對照,依然不能解決問題。后來
直接在C#代碼里綁定,無意中發現item1居然為null,料想原來是visual tree出了問題:定義的ValidatorItem根本沒有加載到控件樹中,雖然使用Validator.Items
是可以成功訪問到的。
于是乎,到處找關于FindName方法的資料,了解到WPF中需要通過RegisterName來注冊NameScope,可是silverlight里根本沒有類似方法。
最終,在這個帖子里找到了解決辦法://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類中需要定義好幾個集合屬性咋辦?
本站文章除注明轉載外,均為本站原創或翻譯。歡迎任何形式的轉載,但請務必注明出處、不得修改原文相關鏈接,如果存在內容上的異議請郵件反饋至chenjj@fc6vip.cn
文章轉載自:網絡轉載