【发布时间】:2014-12-18 04:07:39
【问题描述】:
我正在尝试设置一个可以在 Xaml 中绑定的自定义附加属性。如果我传递纯字符串,它工作正常:
MyProperties.h:
#pragma once
#include "pch.h"
namespace SimpleApp
{
namespace WUX = Windows::UI::Xaml;
public ref class MyProperties sealed : public WUX::DependencyObject
{
private:
static WUX::DependencyProperty^ _MyValue;
public:
MyProperties::MyProperties();
static property WUX::DependencyProperty^ MyValue
{
WUX::DependencyProperty^ get()
{
return _MyValue;
}
};
static Platform::String^ GetMyValue(WUX::UIElement^ element);
static void SetMyValue(WUX::UIElement^ element, Platform::String^ value);
};
}
MyProperties.cpp:
#include "pch.h"
#include "MyProperties.h"
using namespace Windows::UI::Xaml;
using namespace SimpleApp;
MyProperties::MyProperties()
{
};
DependencyProperty^ MyProperties::_MyValue = DependencyProperty::RegisterAttached(
"MyValue",
Platform::String::typeid,
MyProperties::typeid,
ref new PropertyMetadata(false)
);
Platform::String^ MyProperties::GetMyValue(UIElement^ element)
{
auto val = safe_cast<Platform::String^>(element->GetValue(_MyValue));
return val;
}
void MyProperties::SetMyValue(UIElement^ element, Platform::String^ stringValue)
{
element->SetValue(_MyValue, stringValue);
OutputDebugString(L"It worked!");
// Also do other stuff
}
Xaml:
<Page
x:Class="SimpleApp.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:SimpleApp"
Width="525"
>
<Grid x:Name="_grid" Width="500" DataContext="{Binding ElementName=_grid}">
<TextBlock local:MyProperties.MyValue="Hello" Text="{Binding Width}" />
</Grid>
</Page>
这可行 - SetMyValue 函数使用传递给它的参数“Hello”执行。
但是,当我尝试对 MyValue 属性使用绑定时,SetMyValue 不会执行。我在 Xaml 中用这个替换 TextBlock:
<TextBlock local:MyProperties.MyValue="{Binding Width}" Text="{Binding Width}" />
我也将 Text 绑定到 Width 以确保它通常可以正常工作。我必须在某处做出魔法声明来说服该属性是可绑定的吗?
NB this question 正在询问类似的问题,但对于 WPF,提问者似乎并没有解决他的问题。
【问题讨论】:
标签: xaml windows-runtime winrt-xaml c++-cx