다음은 C ++ (Visual Studio C ++ 2017)에서 동적으로 버튼을 만드는 방법입니다.
Button^ myButton = ref new Button();
myButton->Content = "Button";
myButton->Height = 80;
myButton->Width = 150;
ContentPanel->Children->Append(myButton);
ContentPanel에서이 버튼을 어떻게 동적으로 제거합니까?
ContentPanel->Children-> RemoveAt(myButton);
작동하지 않고 오류가 발생합니다. 내가 여기서 뭘 잘못하고 있니?
완전한 예 :
<Page
x:Class="App3.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:App3"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<StackPanel x:Name="ContentPanel">
<TextBlock HorizontalAlignment="Left" Text="Hello!" />
</StackPanel>
<Button x:Name="InputButton" Content="Click" Click="InputButton_Click"/>
</Grid>
// MainPage.xaml.cpp
// Implementation of the MainPage class.
//
#include "pch.h"
#include "MainPage.xaml.h"
using namespace App3;
using namespace Platform;
using namespace Windows::Foundation;
using namespace Windows::Foundation::Collections;
using namespace Windows::UI::Xaml;
using namespace Windows::UI::Xaml::Controls;
using namespace Windows::UI::Xaml::Controls::Primitives;
using namespace Windows::UI::Xaml::Data;
using namespace Windows::UI::Xaml::Input;
using namespace Windows::UI::Xaml::Media;
using namespace Windows::UI::Xaml::Navigation;
MainPage::MainPage()
{
InitializeComponent();
}
void App3::MainPage::InputButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
{
Button^ myButton = ref new Button();
if (myButton != nullptr)
{
myButton->Margin = Thickness(10);
myButton->Content = "myButton";
myButton->Height = 80;
myButton->Width = 150;
myButton->Foreground = ref new SolidColorBrush (Windows::UI::Colors::Lavender);
myButton->Background = ref new SolidColorBrush(Windows::UI::Colors::Olive);
ContentPanel->Children->Append(myButton);
}
else
ContentPanel->Children->RemoveAt(myButton);
}
또한 (myButton! = nullptr)은 'myButton'이 이미 동적으로 생성되었는지 여부를 테스트하는 적절한 방법이 아니라고 생각합니다 ( 'InputButton_Click'의 이전 호출에서).
RemoveAt
제거 할 항목의 인덱스를 사용합니다. 새 항목을 추가 할 때 어딘가에 저장하고 나중에 제거 할 때 사용해야합니다.
m_button_index = ContentPanel->Children->Size;
ContentPanel->Children->Append(myButton);
}
else
ContentPanel->Children->RemoveAt(m_button_index);
또한 myButton != nullptr
할당 된 버튼이 null이 아니거나 예외가 발생하여 코드가 항상 버튼을 추가하므로 검사 는 의미가 없습니다.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다