【问题标题】:How to create and use an AttachedProperty in C++/Cx and XAML?如何在 C++/Cx 和 XAML 中创建和使用 AttachedProperty?
【发布时间】:2012-11-16 14:51:38
【问题描述】:

我想在我的 C++/Cx WinRT 项目中创建一个附加属性。当我这样做时,XAML 编译器会抱怨我正在使用未知属性。

我在 cpp 文件中声明我的附加属性:

/*--------------------------------------------------------------------
    Forward Declarations
--------------------------------------------------------------------*/
namespace
{
    void
    StateChanged(
        DependencyObject^ target,
        DependencyPropertyChangedEventArgs^ args);
}

/*--------------------------------------------------------------------
    DependancyProperty setup for the view model
--------------------------------------------------------------------*/
namespace
{
DependencyProperty^ _stateProperty =
    DependencyProperty::RegisterAttached(
        "State",
        TypeName(Platform::String::typeid),
        TypeName(VisualStateManagerBindingHelper::typeid),
        ref new PropertyMetadata(nullptr, ref new PropertyChangedCallback(&StateChanged)));
}

namespace
{
    void
    StateChanged(
        DependencyObject^ target,
        DependencyPropertyChangedEventArgs^ args)
    {
        if (args->NewValue != nullptr)
        {
            VisualStateManager::GoToState(safe_cast<Control^>(target), safe_cast<String^>(args->NewValue), true);
        }
    }
}

在我的 XAML 文件中,我尝试使用附加属性:

<UserControl
    xmlns:local="using:MyCustomNamespace"
    ...

    <Grid Grid.Column="1" local:VisualStateManagerBindingHelper.State="{Binding Path=SomeViewModelProperty, Mode=TwoWay}">
        ...

编译时遇到这个错误:

XamlCompiler 错误 WMC0010:元素“网格”上的未知可附加成员“VisualStateManagerBindingHelper.State”

在我看来,XAML 编译器似乎应该在某处获得允许此附加属性的提示,但我不知道如何给出该提示。 This article 在同一主题上建议 DependancyProperty 应该是公共的。我不完全确定如何在 C++ 中做到这一点。

我的最终目标是将视觉状态组的状态绑定到某个视图模型属性。在this question 中接受的答案中概述了执行此操作的方法。不幸的是,那里提供的代码是 C#,我似乎无法正确地将其转换为 C++。

最后,我注意到 Visual Studio 的新项目模板附带的 SuspensionManager 几乎和我一样定义了一个附加属性,但它们没有显示任何使用它的示例。这让我感觉自己走上了正轨,但错过了一小部分难题。

【问题讨论】:

    标签: windows xaml visual-c++ dependency-properties c++-cx


    【解决方案1】:

    我找到了一个回答了我的问题的网站!正如我所怀疑的,您需要以非常特定的方式定义您的类,以便 XAML 预处理器了解您的附加属性。 here 提供所有要求以及代码示例。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-11-06
      • 2012-05-28
      • 1970-01-01
      • 2016-10-02
      • 2022-08-19
      • 1970-01-01
      • 2020-02-21
      • 2013-02-20
      相关资源
      最近更新 更多