Win10系列:VC++数据绑定

数据绑定是一种将后台数据绑定到前台控件的机制,通常用于动态地将对象或集合中所保存的数据显示到前台界面中。本节通过一个具体的示例来说明在Windows应用商店应用中如何通过数据绑定将保存在集合中的数据显示到前台界面中。

在Visual Staudio 2012中新建一个Visual C++的Windows应用商店的空白应用程序项目,并命名为BindingDemo。接着打开MainPage.xaml.h头文件,添加如下的代码:

//定义类FeedItem

[Windows::UI::Xaml::Data::Bindable]

public ref class FeedItem sealed

{

internal:

    //FeedItem构造函数

    FeedItem(void){}

public:

    //声明属性Country

    property Platform::String^ Country;

    //声明属性City

    property Platform::String^ City;

};

在上面的代码中,首先使用"[Windows::UI::Xaml::Data::Bindable]"语句定义一个可以绑定到前台界面的FeedItem类,然后在此类中定义构造函数FeedItem,接着声明两个String类型的属性 Country和City。

定义了FeedItem类以后,接着布局前台界面。打开MainPage.xaml文件,并在Grid元素中添加如下代码:

<ListBox x:Name="InfoListBox" ItemsSource="{Binding}" Foreground="Black" Width="200" Height="260" FontSize="24">

<ListBox.ItemTemplate>

<DataTemplate>

<StackPanel>

<TextBlock Text="{Binding Country}"/>

<TextBlock Text="{Binding City}"/>

</StackPanel>

</DataTemplate>

</ListBox.ItemTemplate>

</ListBox>

在上面的代码中,添加了一个名为"InfoListBox"的ListBox控件,并将此控件的ItemsSource属性设置为{Binding},表示在后台所创建的集合将绑定到这个属性。接着为ListBox控件添加DataTemplate模版,并在此模版中添加两个TextBlock控件,用FeedItem类的Country属性和City属性分别绑定到这两个TextBlock控件的Text属性上。

布局了前台界面以后,接着打开MainPage.xaml.cpp源文件,并添加如下的代码:

MainPage::MainPage()

{

    InitializeComponent();

    //创建一个Vector<FeedItem^>类型的集合items

    Platform::Collections::Vector<FeedItem^>^ items=ref new Platform::Collections::Vector<FeedItem^>();

    //创建FeedItem类的对象feedItemCN

    FeedItem^ feedItemCN = ref new FeedItem();

    feedItemCN->Country="中国";

    feedItemCN->City="北京";

    //创建FeedItem类的对象feedItemUS

    FeedItem^ feedItemUS = ref new FeedItem();

    feedItemUS->Country="美国";

    feedItemUS->City="纽约";

    //创建FeedItem类的对象feedItemUK

    FeedItem^ feedItemUK = ref new FeedItem();

    feedItemUK->Country="英国";

    feedItemUK->City="伦敦";

    //将上述对象保存到items集合中

    items->Append(feedItemCN);

    items->Append(feedItemUS);

    items->Append(feedItemUK);

    //设置ListBox控件的DataContext属性

    InfoListBox->DataContext=items;

}

在上面的代码中,首先创建一个Vector<FeedItem ^>类型的集合items,接着分别创建FeedItem类的三个对象feedItemCN、feedItemUS和feedItemUK,并给这三个对象中的Country属性和City属性赋值。然后调用items集合的Append函数,分别将对象feedItemCN、feedItemUS和feedItemUK添加到此集合中。最后将items集合赋值给名为"InfoComboBox"的ComboBox控件的DataContext属性。

运行BindingDemo项目,前台界面如图20-2所示。

图20-2 items集合中的数据

原文地址:https://www.cnblogs.com/finehappy/p/6645515.html