Search code examples
.netwpf.net-4.0attached-properties

Set value for AttachedProperty with own type


I have created a class like

public class ContextMenuSetting {
    public bool ContextMenuAllowed { get; set; }
    public string GridKey { get; set; }
}

And a AttachedProperty like:

public static readonly DependencyProperty ContextMenuSettingsProperty = DependencyProperty.RegisterAttached("ContextMenuSettings", typeof(ContextMenuSetting), typeof(BarItemLink), null);

public static void SetContextMenuSettings(this BarItemLink target, ContextMenuSetting contextMenuSetting) {
    target.SetValue(ContextMenuSettingsProperty, contextMenuSetting);
}

public static ContextMenuSetting GetContextMenuSettings(this DependencyObject target) {
    return (ContextMenuSetting)target.GetValue(ContextMenuSettingsProperty);
}

I have now the following use of BarItemLink in xaml:

<dxb:BarItemLink BarItemName="newActivity"  />

Can somebody help me, how I can set now a Value for the AttachedProperty ContextMenuSettings for BarButtonLink?

edit - update solution:

With Charleh's help, i have found the solution:

<dxb:BarItemLink BarItemName="newActivity">
   <pcce:BarItemLinkExtensions.ContextMenuSettings >
       <pcce:ContextMenuSettings ContextMenuAllowed="True" GridKey="hallo"/>
   </pcce:BarItemLinkExtensions.ContextMenuSettings>
</dxb:BarItemLink>

Solution

  • Have you included the ContextMenuSetting classes namespace in the XAML?

    xmlns:ctxmenu="SomeNameSpace"
    
    <dxb:BarItemLink BarItemName="blah" ctxmenu:ContextMenuSetting.ContextMenuSettings="blah" />
    

    Edit: if you want to set a custom type you can use either a TypeConverter (if you want to enter a string value) or use the extended syntax

    <dxb:BarItemLink BarItemName="blah">
       <ctxMenu:ContextMenuSetting.ContextMenuSettings SomeProperty="SomeValue" />
    </dxb:BarItemLink>
    

    Or TypeConverter if you want to do this:

    <dxb:BarItemLink BarItemName="blah" ctxmenu:ContextMenuSetting.ContextMenuSettings="blah" />
    

    Which will interpret the string value "blah" and use a TypeConverter to create the proper type in code

    http://msdn.microsoft.com/en-us/library/aa970913.aspx