深入浅出Windows 10 通用应用开发学习笔记(C++) 3-1

来源:互联网 发布:js文本框获得焦点 编辑:程序博客网 时间:2024/05/17 10:27

为了防止自己忘记,特意开了CSDN做笔记。

最近电脑升级到了Windows 10 买了深入浅出:Windows10 通用应用开发 ,由于本人一般习惯用C和C++进行开发,而该书大部分代码为C#的,虽说都能看懂使用,但是开发的时候还是想基于C++进行。因此在学习时用C++来重新实现,进行练习。

3-1例程为动态加载XAML文件,该例程使用XamlReader::Load()加载XAML字符串生成一个按钮以及加载XAML文件生成一个矩形。

在这里最重要的问题是,C#中有 await 关键字可以等待异步操作返回,而C++中需要自己去处理异步操作返回。

MainPage.xaml.cpp 部分代码
void example_3_1::MainPage::bt_addXAML_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e){String ^buttonXAML = "<Button xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'  " +" Content=\"加载XAML文件\"  Foreground=\"Red\"></Button>";Button ^btnRed = (Button ^)XamlReader::Load(buttonXAML);btnRed->Click += ref new RoutedEventHandler(this, &MainPage::btnRed_Click);MainPage::sp_show->Children->Append(btnRed);}void example_3_1::MainPage::btnRed_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e){create_task(Package::Current->InstalledLocation->GetFileAsync("Rectangle.xaml")).then([this](StorageFile^ file){if (file){create_task(FileIO::ReadTextAsync(file)).then([this](Platform::String ^ xaml){if (xaml){rectangle = (Rectangle ^)XamlReader::Load(xaml);MainPage::sp_show->Children->Append(rectangle);}});}});}
MainPage.xaml.h部分代码
public:
property Shapes::Rectangle ^rectangle;private:void bt_addXAML_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);void btnRed_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);

Rectangle.xaml文件代码
<Rectangle xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"          xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"         Height="100" Width="200">    <Rectangle.Fill>        <LinearGradientBrush>            <GradientStop Color="Black" Offset="0"/>            <GradientStop Color="Red" Offset="0.5"/>            <GradientStop Color="Black" Offset="1"/>        </LinearGradientBrush>    </Rectangle.Fill></Rectangle>
在做的时候多次想要放弃C++,但那样就不能充分锻炼自己的编程水平,(并不是说C#不好,毕竟先入为主,C#里有很多C++中很难实现的东西,比如await关键字这样的操作),因此在网上查了很多异步编程的一些资料,感觉到编程路漫漫,自己需要学习的东西实在太多了。




0 0
原创粉丝点击