【发布时间】:2017-10-13 01:24:54
【问题描述】:
这就是我在 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”时)
【问题讨论】:
-
您的错误是什么?请问可以提供minimal reproducible example吗?
-
它产生两个错误:E1767 和 C2664:错误(活动)E1767 函数“Windows::UI::Xaml::Controls::UIElementCollection::RemoveAt”不能用给定的参数列表 App2 调用c:\Users\ZM\Documents\Visual Studio 2017\Projects\App2\App2\MainPage.xaml.cpp 79 错误 C2664 'void Windows::UI::Xaml::Controls::UIElementCollection::RemoveAt(unsigned int)' : 无法将参数 1 从 'Windows::UI::Xaml::Controls::Button ^' 转换为 'unsigned int' App2 c:\users\zm\documents\visual studio 2017\projects\app2\app2\mainpage.xaml .cpp 79
-
edit您的问题请添加更多信息!
-
你可能过于简单了。
标签: visual-studio xaml uwp c++-cx