2011-08-22 138 views
1

我试图将数据值绑定到附加属性。但是,它只是没有得到它的工作。WP7:绑定到附加属性

我定义它想:

public static class MyClass 
{ 
    public static readonly DependencyProperty MyPropertyProperty = 
     DependencyProperty.RegisterAttached("MyProperty", typeof(string), 
     typeof(MyClass), new PropertyMetadata(null)); 

    public static string GetMyProperty(DependencyObject d) 
    { 
     return (string)d.GetValue(MyPropertyProperty); 
    } 

    public static void SetMyProperty(DependencyObject d, string value) 
    { 
     d.SetValue(MyPropertyProperty, value); 
    } 
} 

现在我用它的XAML看起来是这样的:

<TextBlock local:MyClass.MyProperty="{Binding MyStringValue}" /> 

我在SetMyProperty方法设置断点,但它永远不会被调用。它不会产生任何错误,它从来没有设置或要求。但是,如果我将XAML中的值更改为固定字符串,它会被调用:

<TextBlock local:MyClass.MyProperty="foobar" /> 

我在想什么?

注:上面的例子中是最小的版本,显示了同样的奇怪的行为。当然,我的实际实施比这更有意义。

在此先感谢您的任何提示!

+1

AFAIR倍率即使get/set方法是必要的WPF/Silverlight可能不会直接调用它们。这就是为什么你的断点没有命中,因为WPF/Silverlight使用反射(只是猜测)或直接使用SetValue。你说它不起作用,值是正确的,但是你的断点没有被击中?然后它就是正常的。抱歉,无法在MSDN中找到此源,但我知道我在某处阅读它。 – dowhilefor

+0

@dowhilefor:这是有道理的。我只是为我寻找却没有发现这事...... –

+0

有你的get/set声明一个错误,应该是: 回报(字符串)d.GetValue(MyPropertyProperty); – cunningdave

回答

4

而且不会绑定曾经触发您SetMyProperty - 如果你需要控制好了当值的变化,你必须使用的PropertyMetadata期望一个“变” -Handler



... new PropertyMetadata(
    null, 
    new PropertyChangedCallback((sender, e) => { 
     var myThis = (MyClass)sender; 
     var changedString = (string)e.NewValue; 
     // To whatever you like with myThis (= the sender object) and changedString (= new value) 
    }) 

+0

太棒了,工作。非常感谢! –

0

将SetMyProperty中的第二个参数的类型更改为Object类型。

你将获得一个绑定的对象,而不是字符串,因为没有价值。

+0

感谢您的回复。刚刚尝试过,但它仍然无法正常工作。 –

+0

这是错误的。你永远不会得到一个Binding对象,他的dp是字符串类型,所以SetMyPropert应该期望一个字符串。 WPF/silverlight将会跟踪如何和何时评估绑定以获得dp或ap的有效值。 – dowhilefor