如何将C++函数绑定到xaml文本块属性

how to bind a C++ function to a xaml text textblock property

本文关键字:xaml 文本 属性 绑定 C++ 函数      更新时间:2023-10-16

我必须学会在UWP上编码(这是我使用windows 10和VS的第一步),所以我尝试做一些非常基本的事情:从一些C++函数更改文本块。

从技术上讲,我的项目很简单:我打开了一个新的可视化C++>Windows>通用>空白应用程序我在MainPage.xaml:中添加了一个文本块

<Page
x:Class="App4.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:App4"
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}">
<TextBlock x:Name="textBlock" HorizontalAlignment="Left" Margin="49,46,0,0" TextWrapping="Wrap" Text="WHAT I WANT TO BIND" VerticalAlignment="Top"/>
</Grid>
</Page>

我试着想办法绑定文本块。我试了好几种方法,都失败了。例如,我添加了一个类TestBindMe:

TestBindMe.h

#pragma once
namespace App4
{
ref class TestBindMe sealed
{
public:
TestBindMe();
property Platform::String^ MySuperString
{
Platform::String^ get() {
return this->mySuperString_;
}
}
private:
Platform::String^ mySuperString_;
};
};

TestBindMe.cpp

#include "pch.h"
#include "TestBindMe.h"
namespace App4
{
TestBindMe::TestBindMe()
{
}
};

我尝试在为Text={x:Bind TestBindMe.get}编辑Text="WHAT I WANT TO BIND"之后构建它

我得到了输出:

1>------ Build started: Project: App4, Configuration: Debug Win32 ------
1>  App.xaml.cpp
1>  MainPage.xaml.cpp
1>  TestBindMe.cpp
1>c:usersuserdocumentsvisual studio 2015projectsapp4app4testbindme.cpp(1): fatal error C1010: unexpected end of file while looking for precompiled header. Did you forget to add '#include "pch.h"' to your source?
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
========== Deploy: 0 succeeded, 0 failed, 0 skipped ==========

正如Clemens所说,{x:Bind}使用页面或用户控件本身作为默认源。

它将在页面或用户控件的代码后面查找属性、字段和方法。若要向{x:Bind}公开视图模型,通常需要向页面或用户控件的代码后面添加新字段或属性。属性路径中的步骤由点(.)分隔,可以包含多个分隔符来遍历连续的子属性。无论用于实现绑定到的对象的编程语言如何,都要使用点分隔符。

因此,我们可以在MainPage的代码后面为{x:Bind}添加一个属性。请注意

对于C++/CX,{x:Bind}无法绑定到页面或数据模型中的专用字段和属性–您需要有一个公共属性才能进行绑定。

有关详细信息,请参阅{x:Bind}标记扩展。

所以我更改了你的TestBindMe.h,就像下面的一样

namespace App4
{
public ref class TestBindMe sealed
{
public:
TestBindMe();
property Platform::String^ MySuperString
{
Platform::String^ get() {
return this->mySuperString_;
}
}
private:
Platform::String^ mySuperString_ = "My Bind Test";
};
}

MainPage.xaml.h中,添加一个名为"ViewModel"的公共属性,其类型为TestBindMe:

#include "MainPage.g.h"
#include "TestBindMe.h"
namespace App4
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public ref class MainPage sealed
{
public:
MainPage();
property App4::TestBindMe^ ViewModel;
};
}

然后在MainPage.xaml.cpp中,初始化ViewModel:

MainPage::MainPage()
{
InitializeComponent();
ViewModel = ref new TestBindMe();
}

之后,我们可以像Text="{x:Bind ViewModel.MySuperString}"一样在XAML中使用{x:Bind}

这是一个简单的示例,您可以在GitHub上找到官方的x:Bind示例。