2017-07-21 76 views
1

我想在StackLayout動態添加一個按鈕被點擊按鈕時「添加」。我寫了stacklayoutname.children.add(button),它沒有給我我正在尋找的東西。添加按鈕,動態地stacklayout

在XAML:

<StackLayout x:Name="layout"> 
    <Button Text="add" Clicked="Addbutton"/> 
</StackLayout> 

在代碼:

private void Addbutton(object sender, EventArgs e) 
{   
    var layout = new StackLayout(); 
    var btn = new Button { Text = "New button", FontSize = 30, TranslationY = 30 }; 
    this.Content = layout; 
    layout.Children.Add(btn); 
} 

這是給唯一的新按鈕,添加按鈕消失,但我想,只要我們點擊添加按鈕,它應該給數新按鈕等於添加按鈕上的點擊次數。

+1

它消失,因爲它是由新的'StackLayout'取代。當你說_should給予等於上加button_點擊數新按鈕的數量,你的意思是你要添加按鈕按每次點擊或'Button'的'Text'點擊只是顯示號碼是多少? – Curiousity

+0

感謝響應,是的,我想補充的許多按鈕的點擊次數,但不只是顯示在按鈕的文本點擊次數。 – sahithi

回答

1

既然你已經有了一個StackLayout,沒有必要添加一個新的,因爲如果你這樣做替換舊。以下將在每次點擊按鈕時向StackLayout添加一個按鈕。

// Define a field for StackLayout 
StackLayout parent; 

public void Addbutton(object sender, EventArgs e) 
{ 
    // Define a new button 
    Button newButton = new Button { Text = "New Button" }; 

    // Creating a binding 
    newButton.SetBinding(Button.CommandProperty, new Binding ("ViewModelProperty")); 

    // Set the binding context after SetBinding method calls for performance reasons 
    newButton.BindingContext = viewModel; 

    // Set StackLayout in XAML to the class field 
    parent = layout; 

    // Add the new button to the StackLayout 
    parent.Children.Add(newButton); 
} 

有關綁定的更多信息,請herehere

+0

由於它得到了工作了me.but我想爲新增加的button.Is可以綁定的命令爲這些按鈕 – sahithi

+0

如何給綁定到這些按鈕 – sahithi

+0

要添加結合(繼續Add按鈕方法)add命令:' newButton.BindingContext = yourViewModel;'和'newButton.SetBinding(Button.CommandProperty,新結合( 「CommandPropertyName」));' –