简体   繁体   中英

XAML - Defining attached properties in custom UserControl

I have a custom UserControl, and I would like to attach custom properties to some contained UI elements.

I tried to achieve it like this, but VS does not accept my XAML code. It says MyProp is not available, or accessible.

<UserControl 
    x:Class="mynamespace.MyDataSourceSelector" 
    xmlns:local="clr-namespace:mynamespace" 
    ... >
    <TabControl>
        <TabItem Header="Tab1" local:MyDataSourceSelector.MyProp="something1"/>  
        <TabItem Header="Tab2" local:MyDataSourceSelector.MyProp="something2"/>
    </TabControl>
<UserControl>

My custom UserControl class looks something like this:

public partial class MyDataSourceSelector: UserControl
{
    ...

    public string MyProp
    {
        get { return (string)GetValue(MyPropProperty); }
        set { SetValue(MyPropProperty, value); }
    }

    public static readonly DependencyProperty MyPropProperty 
        = DependencyProperty.Register(
            "MyProp", 
            typeof(string), 
            typeof(MyDataSourceSelector), 
            new PropertyMetadata(null)
        );

}

I would like to bind a value for every tab, then read out the active tab's MyProp value, when needed.

How can I do this?

You messed up a few things. In your case you should declaring the extension properties like

public static class TabItemExtensions
{
    public static void SetMyProp(TabItem element, string value)
    {
        element.SetValue(MyPropProperty, value);
    }

    public static string GetMyProp(TabItem element)
    {
        return (string)element.GetValue(MyPropProperty);
    }

    public static readonly DependencyProperty MyPropProperty
        = DependencyProperty.RegisterAttached(
            "MyProp",
            typeof(string),
            typeof(TabItemExtensions),
            new PropertyMetadata(null)
        );
}

and use it like

<TabItem Header="Tab1" local:TabItemExtensions.MyProp="something1"/>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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