Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Attached Properties as XAML Elements

I've got a class of attached properties:

public static class XamlProps
{
    #region Attached Properties

    private static readonly DependencyProperty FooProperty = DependencyProperty.RegisterAttached(
        "Foo",
        typeof(string),
        typeof(XamlProps),
        null);

    public static void SetFoo(DependencyObject obj, string action)
    {
        obj.SetValue(FooProperty, action);
    }
}

And I use these properties in my XAML:

<Border me:XamlProps.Foo="Foo to the Bar">

But now I want a larger value in this property, so I'd like to use it as an element:

<Border>
    <me:XamlProps.Foo>Foo to the Bar</me:XamlProps.Foo>
</Border>

But now Silverlight doesn't call SetFoo() anymore. How do I get this to work?

On Windows Phone 7 if it matters.

like image 492
Hounshell Avatar asked Mar 10 '11 23:03

Hounshell


People also ask

What is attached properties and how do you register it?

An 'attached' property is a concept defined by Extensible Application Markup Language (XAML). It is intended to be used as a type of global property that can be set on any object.

What is attached property in xamarin forms?

Attached properties enable an object to assign a value for a property that its own class doesn't define. For example, child elements can use attached properties to inform their parent element of how they are to be presented in the user interface.

What is dependency property in WPF?

Windows Presentation Foundation (WPF) provides a set of services that can be used to extend the functionality of a type's property. Collectively, these services are referred to as the WPF property system. A property that's backed by the WPF property system is known as a dependency property.


2 Answers

You'll need to specify the type if you use that syntax:

<Border>
    <me:XamlProps.Foo>
        <sys:String>Foo to the Bar</sys:String>
    </me:XamlProps.Foo>
</Border>

Where the sys namespace maps to System. You also need to define GetFoo ...

Probably a copy-paste typo, but in the registration

typeof(XamlActions)

should be

typeof(XamlProps)
like image 104
Damian Avatar answered Oct 19 '22 14:10

Damian


You should never rely on the SetFoo being called. Anything can simply call SetValue(FooProperty, "blah") and bypass it.

You should define a PropertyChangedCallback in your DependencyProperty.Register call to be notified of changes.

like image 34
CodeNaked Avatar answered Oct 19 '22 14:10

CodeNaked