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