【发布时间】:2016-04-14 13:33:28
【问题描述】:
我需要将控件的属性绑定到 XAML 中的附加属性(以便附加属性成为绑定的源),但我不知道该怎么做——VS2015 给了我“值不在预期范围内”错误,并且在我运行应用程序时出现异常。
下面显示的技术在 WPF 中完美运行。
这是演示问题的示例应用程序。
AttachedPropertyTest.cs:
namespace App7
{
public static class AttachedPropertyTest
{
public static readonly DependencyProperty FooProperty = DependencyProperty.RegisterAttached(
"Foo", typeof(string), typeof(AttachedPropertyTest), new PropertyMetadata("Hello world!"));
public static void SetFoo(DependencyObject element, string value)
{
element.SetValue(FooProperty, value);
}
public static string GetFoo(DependencyObject element)
{
return (string) element.GetValue(FooProperty);
}
}
}
MainPage.xaml:
<!-- Based on the default MainPage.xaml template from VS2015.
The only thing added is the TextBlock inside the Grid. -->
<Page x:Class="App7.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:App7"
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 Text="{Binding Path=(local:AttachedPropertyTest.Foo), RelativeSource={RelativeSource Self}}"
HorizontalAlignment="Center" VerticalAlignment="Center"/>
</Grid>
</Page>
而不是显示“Hello world!” (这是 Foo 附加属性的默认值)在上面的 TextBlock 上,我得到了从 InitializeComponent 抛出的 XamlParseException。像往常一样,异常对象不包含任何有用的信息。
有趣的是,如果我尝试绑定到任何标准(内置于框架中)附加属性(如 (Grid.Row)),则不会发生这种情况,因此 XAML 解析器似乎不允许我使用自定义附加属性提供者,这很荒谬......
那么正确的做法是什么?
【问题讨论】:
标签: c# xaml visual-studio-2015 winrt-xaml uwp