三十七:採用用字符串構造DataTemplate實現CheckListBox的CustomControl

爲了方便大家學習,請單擊此處下載該程序的代碼。
  這次Themes\CheckListBox.xaml的內容相當簡單:

    1 <ResourceDictionary
    2    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    3    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    4    xmlns:local="clr-namespace:Eallies.OA.UI.Controls.Common">
    5 
    6     <Style TargetType="{x:Type local:CheckListBox}" BasedOn="{StaticResource {x:Type ListBox}}" />
    7 
    8 </ResourceDictionary>
  其具體的ItemTemplate,我們可以在OnInitialized方法中實現:
    1     protected override void OnInitialized(EventArgs e)
    2     {
    3         base.OnInitialized(e);
    4 
    5         string template = string.Format("<DataTemplate xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"><CheckBox Name=\"chkCheckBox\" Tag=\"{{Binding Path={0}}}\" Content=\"{{Binding Path={1}}}\" /></DataTemplate>", this.ItemValuePath, this.ItemContentPath);
    6         this.ItemTemplate = XamlReader.Load(XmlReader.Create(new StringReader(template))) as DataTemplate;
    7     }
  其它代碼就很以前的方案一樣了。由於這裏沒有Converter,所以代碼會簡單很多。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章