首页 > 解决方案 > 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>

标签: c++uwpvisual-studio-2019uwp-xamldatacontext

解决方案


如果要在 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>

推荐阅读