![](/img/trans.png)
[英]Navigation Concept (User Control to Xaml page) in Windows Phone app
[英]StackPanel with User Controls in another User Control in Xaml Windows Phone
如何從C#代碼向UserControl中的StackPanel添加子項? 我應該為其創建類似DependencyProperty的東西嗎?
因為很容易在UserControl中設置諸如TextBlock的Text之類的屬性,所以我不知道在使用CodeBehind動態地進行設置時如何向StackPanel添加項目。
StackPanel
僅用於最基本的布局情況。 根據需要使用某種ListBox
或ItemsControl
更好。 您可以將集合DependencyProperty
添加到UserControl
然后執行以下操作:
在UserControl
:
<ItemsControl ItemsSource="{Binding YourCollectionDependencyProperty, RelativeSource={
RelativeSource AncestorType={x:Type YourPrefix:YourUserControl}}}" ... />
然后,您可以將數據從UserControl
外部綁定到UserControl
另一個集合屬性:
外部UserControl
:
<YourPrefix:YourUserControl YourCollectionDependencyProperty="{Binding Items}" ... />
然后,添加要在UserControl
顯示的新項目就像將項目添加到Items
集合一樣簡單:
Items.Add(someNewObject);
請閱讀MSDN上的“ 數據綁定概述”頁面,以獲取有關數據綁定的更多信息。
是的,您可以執行以下操作(這只是一個示例):
TextBlock printTextBlock = new TextBlock();
printTextBlock.Text = "Hello, World!";
//MainStackPanel below is the name given to your control in xaml
MainStackPanel.Children.Add(printTextBlock);
資料來源:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.