c++ - This->DataContext not working in uwp c++/cf in Visual Studio 2019 in C++
问题描述
我正在使用 UWP 为服务器应用程序创建一个应用程序,并且我在 C++ 中创建了一个类 serverclass.h,其中有一个字符串输出。现在我想在 xaml 的文本框中打印这个输出。我附上了下面的代码。当我使用 this->DataContext=ser; 它给了我一个错误:“函数 Windows::UI::Xaml::FrameworkElement::DataContext::set 不能用给定的参数列表调用”。这里有什么问题?
主页.xaml.cpp
serverclass ser;
MainPage::MainPage()
{
InitializeComponent();
this->DataContext = ser;
}
void App1::MainPage::Button_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
{
ser.output = "hey";
ser.connect();
}
服务器类.h
class serverclass
{
public:
string output;
}
"mainpage.xaml"
<TextBox Text="{Binding output}" Height="50" FontSize="30px">
</TextBox>
解决方案
如果要在 xaml 的文本框中打印字符串输出,可以使用引用文档和示例的数据绑定。
对于您提到的场景,您可以检查以下代码:serverclass.h
namespace YourAppName{//Put the serverclass into the namespace
public ref class serverclass sealed : Windows::UI::Xaml::Data::INotifyPropertyChanged
{
private:
Platform::String^ output;
public:
virtual event Windows::UI::Xaml::Data::PropertyChangedEventHandler^ PropertyChanged;
serverclass()
{ }
property Platform::String^ Output {
Platform::String^ get() { return output; }
void set(Platform::String^ value) {
if (output != value)
{
output = value;
PropertyChanged(this, ref new Windows::UI::Xaml::Data::PropertyChangedEventArgs("Output"));
}
}
};
};
}
主页.xaml.h
public ref class MainPage sealed
{
public:
MainPage();
property serverclass^ Ser {
serverclass^ get() { return ser; }
void set(serverclass^ value) {
ser = value;
}
}
private:
serverclass^ ser;
void Button_Click(Platform::Object^ sender,
Windows::UI::Xaml::RoutedEventArgs^ e);
};
MainPage.xaml.cpp
MainPage::MainPage()
{
InitializeComponent();
this->ser = ref new serverclass();
ser->Output = "world";
this->DataContext = ser;
}
void DataContextSample::MainPage::Button_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
{
ser->Output = "hello";
}
主页.xaml
<StackPanel>
<TextBox Text="{x:Bind Ser.Output,Mode=TwoWay}" Width="100" Height="30" Margin="10"/>
<Button Click="Button_Click" Content="click me"/>
</StackPanel>
推荐阅读
- .net - EF Core ForeignKey-like 关系
- c# - 需要帮助为 Dropbox 编写下载器
- keras - 使用 Keras ImageDataGenerator 增强边界框
- ruby-on-rails - Graphhopper - 覆盖权重类并将其集成到 Ruby on Rails
- cucumber-jvm - 如果一个场景失败,继续黄瓜特征文件中的下一个场景
- java - Spring 集成中的成功通道是动态的
- c# - 检索数据网格上的特定行
- php - 如何显示用户的最后记录
- android - 试图从类 androidx.room.CoroutinesRoom$Companion 访问类 kotlin.jvm.internal.DefaultConstructorMarker
- c# - 自动更新 Azure 身份验证的最佳方法是什么?