【发布时间】:2016-05-30 16:39:29
【问题描述】:
我必须学习在 UWP 上编码(这是我使用 Windows 10 和 VS 的第一步),所以我尝试做一些非常基本的事情:从某个 C++ 函数更改文本块。
从技术上讲,我的项目非常简单:我打开了一个新的 Visual 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:\users\user\documents\visual studio 2015\projects\app4\app4\testbindme.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 ==========
【问题讨论】:
-
如果它类似于带有 C# 的 WPF,我希望
{Bind MySuperString}足够给定TestBindMe的实例作为数据上下文。 -
@chris 我得到了
Bind is not supported in a Windows Universal Project -
对不起,
{x:Bind MySuperString}。我假设它的工作原理与常规 WPF 大致相同,但无论如何我只是把它扔在那里。 -
@Chris:我得到了
Invalid binding path 'MySuperString' : Property 'MySuperString' can't be found on type 'MainPage' -
{x:Bind ...}仅适用于在同一类中声明的属性(例如此处的 MainPage)。您通常有一个名为 ViewModel 的属性(此处为 TestBindMe 类型),并编写类似{x:Bind ViewModel.MySuperString}的绑定。或者,您可以将 MainPage 的 DataContext 属性设置为 TestBindMe 的实例,并使用常规绑定,例如{Binding MySuperString}。