XAML ContentProperty集合屬性

2022-01-17 01:23:12 字數 1837 閱讀 6264

用過wpf的童鞋都知道,panel或者itemscontrol之類的控制項能夠在xaml裡直接為它們設定子項:

panel之類的控制項,它們的子項都是在children這個屬性裡。

itemscontrol之類的控制項,則是在items這個屬性裡。

那麼它們在xaml裡是怎麼做到不需要用到類似如下的方法而直接對子項賦值呢?

在panel的**裡,有這樣一部分**:

[contentproperty("children")]

public class panel

}

這段**裡,contentproperty是註明children屬性是作為panel的子項集合屬性。這樣在xaml中,就可以省略掉panel.children而直接給panel的子項賦值了。

相應的,在itemscontrol裡也有這樣的**:

[contentpropery("items")]

public class itemscontrol

}

如果我們自己的類也要定義乙個這樣的東西,怎麼辦才好呢?

為類加上contentproperty,然後設定乙個集合屬性。

根據msdn上的說明,我們只需要在類裡這樣做:

[contentproperty("children")]

public class test

}

這樣呢,我們就可以直接在xaml裡為test設定string子項了。

有童鞋會發現,這裡是帶set的,為何之前的panel和itemscontrol裡是沒有set的呢?

因為有時候,我們的children是有特殊功能的,不能讓xaml對children屬性進行賦值,只能讓我們的類進行初始化。

在panel裡,children是uielementcollection,它附帶的功能是每當你add和remove控制項的時候,會自動的設定該控制項的parent等等之類的資訊。

如果我們自己的類,在子項增刪時需要呼叫其它**,那麼,我們就需要自己建立乙個集合類。

根據msdn上的說法,只要我們的集合類繼承ilist<>介面即可。

[contentproperty(children)]

public class test

private testcollection _children;

public testcollection children }

}public class testcollection : ilist

但是作者在實際測試的時候遇到了乙個問題,無論如何xaml也不認可沒有set的children屬性。

研究了好一陣後,發現只要把ilist改為collection就可以達到目的了。(當然實際使用的時候不是string)

[contentproperty("children")]

public class test

private testcollection _children;

public testcollection children }

}public class testcollection : collection

protected override void insertitem(int index, uielement item)

protected override void removeitem(int index)

protected override void setitem(int index, uielement item)

}

android layout weight屬性學習

雖然這個android layout weight屬性很怪異,但幸運的是我們達到了目標 按比例顯示linearlayout內各個子控制項,需設定android layout width 0dp 如果為豎直方向的設定android layout height 0dp 在這種情況下某子個控制項占用lin...

ios autoresizingMask屬性的研究

在 uiview 中有乙個autoresizingmask的屬性,它對應的是乙個列舉的值 如下 屬性的意思就是自動調整子控制項與父控制項中間的位置,寬高。1 2 3 4 5 6 7 8 9 enum uiviewautoresizingnone就是不自動調整。uiviewautoresizingfl...

windowSoftInputMode屬性詳解

android windowsoftinputmode是activity主視窗與軟鍵盤的互動模式,可以用來避免輸入法面板遮擋問題,是android1.5後的乙個新特性。這個屬效能影響兩件事情 一 當有焦點產生時,軟鍵盤是隱藏還是顯示。二 是否減少活動主視窗大小以便騰出空間放軟鍵盤。它的設定必須是下面...