无法绑定到Windows 8 Store Apps中的附加属性

时间:2012-12-03 02:57:22

标签: c# xaml windows-8 windows-runtime

我有一个附加属性,它似乎不会让我绑定到Windows 8中的附加属性。我可以在Silverlight / WPF中自由使用这种方式,但我不知道为什么它不会让我。 MSDN论坛上的一篇文章表示它是通过Windows 8 Release修复的,我现在已经发布,但它无法正常工作。它说“价值不在预期范围内”..

    public static class CountHelper
{
    public static readonly DependencyProperty TitleProperty =
        DependencyProperty.RegisterAttached("Title", typeof (string), typeof (CountHelper), new PropertyMetadata(default(string)));

    public static void SetTitle(UIElement element, string value)
    {
        element.SetValue(TitleProperty, value);
    }

    public static string GetTitle(UIElement element)
    {
        return (string) element.GetValue(TitleProperty);
    }
}

XAML文件

    <TextBlock local:CountHelper.Title="Hello"  Text="{Binding Path=(local:CountHelper.Title)}"/>

1 个答案:

答案 0 :(得分:4)

你的DataContext是什么?也许您应该将ElementName属性添加到绑定中,以将上下文设置为您的控件。

*编辑 - 这对我来说很好:

using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

namespace App75
{
    public static class CountHelper
    {
        public static readonly DependencyProperty TitleProperty =
            DependencyProperty.RegisterAttached("Title", typeof(string), typeof(CountHelper), new PropertyMetadata(default(string)));

        public static void SetTitle(UIElement element, string value)
        {
            element.SetValue(TitleProperty, value);
        }

        public static string GetTitle(UIElement element)
        {
            return (string)element.GetValue(TitleProperty);
        }
    }

    public sealed partial class MainPage : Page
    {
        public MainPage()
        {
            this.InitializeComponent();
        }
    }
}


<Page
    x:Class="App75.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:App75"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <Grid
        Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
        <TextBlock
            x:Name="tb"
            local:CountHelper.Title="Hello"
            Text="{Binding Path=(local:CountHelper.Title), ElementName=tb}" />
    </Grid>
</Page>