简体   繁体   English

未通过UWP中的绑定设置附加的行为属性

[英]Attached Behavior property not being set by binding in UWP

I created a behavior class with a dependency property that I want to attach to a control in my view (XAML). 我创建了一个具有依赖项属性的行为类,该属性要附加到视图(XAML)中的控件上。 I am using MVVM and I need to set this attached property by binding it to a property in my ViewModel, but it does not get set. 我正在使用MVVM,我需要通过将其绑定到ViewModel中的属性来设置此附加属性,但未设置它。 Here is a simplified version of what I want to do: 这是我想要做的简化版本:

Behavior Class: 行为类别:

public static class TestBehavior
{
    public static readonly DependencyProperty SomeStringProperty =
        DependencyProperty.Register("SomeString", typeof(string), typeof(TestBehavior), new PropertyMetadata(""));

    public static string GetSomeString(DependencyObject o)
    {
        return (string)o.GetValue(SomeStringProperty);
    }

    public static void SetSomeString(DependencyObject o, string value)
    {
        o.SetValue(SomeStringProperty, value);
    }

}

XAML: XAML:

<TextBlock Text="{Binding ViewModelProperty}" local:TestBehavior.SomeString="{Binding ViewModelProperty}" />

The "Text" property of the TextBlock binds correctly, but the "SomeString" property of the behavior does not. TextBlock的“ Text”属性可以正确绑定,但是行为的“ SomeString”属性不能正确绑定。

Interestingly - if I "hard code" the behavior property to a value it does get set. 有趣的是-如果我将行为属性“硬编码”为一个值,则它会被设置。 For example: 例如:

<TextBlock Text="{Binding TestValue}" local:TestBehavior.SomeString="Foo" /> <!-- This Works --> 

Any ideas why the binding to the behavior property does not work? 有什么想法为什么绑定到行为属性不起作用?

What do you expect the attached behaviour to do? 您期望附加行为如何处理?

Are you determining that the attached property is/isn't working by setting a breakpoint on the GetSomeString / SetSomeString methods? 您是否通过在GetSomeString / SetSomeString方法上设置断点来确定附加属性是否正常工作? If so, this won't work with binding as the Get/Set methods aren't called when binding is used. 如果是这样,这将不适用于绑定,因为使用绑定时不会调用Get / Set方法。

If you want to react when the attached property changes irrespective of whether it's via binding or not then use the PropertyChangedCallback of the PropertyMetadata specified in the Register call. 如果要在附加属性发生更改时做出反应,而不管它是否通过绑定,请使用Register调用中指定的PropertyChangedCallbackPropertyMetadata

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM