Silverlight 4 - 如何在Style中设置Custom Attached Dependency属性?

时间:2011-05-16 18:07:38

标签: silverlight-4.0 dependency-properties styles attached-properties

我的根ResourceDictionary中有以下内容。 Foreground = Red部分有效,但自定义附加依赖项属性未设置。

我可以通过代码手动设置它,但我显然希望避免为每个文本框设置它。这在Silverlight中有效吗?我已经看过一些关于在WPF中执行此操作的帖子,我的代码看起来是正确的(对我而言)。

<Style TargetType="TextBox">
    <Setter Property="controls:TextBoxContextMenu.HasContextMenu" Value="True" />
    <Setter Property="Foreground" Value="Red" />
</Style>


/// <summary>
    /// Gets the value of the HasContextMenu attached property for a specified TextBox.
    /// </summary>
    /// <param name="element">The TextBox from which the property value is read.</param>
    /// <returns>The HasContextMenu property value for the TextBox.</returns>
    public static bool GetHasContextMenu(TextBox element)
    {
        if (element == null)
        {
            throw new ArgumentNullException("element");
        }
        return (bool)element.GetValue(HasContextMenuProperty);
    }

    /// <summary>
    /// Sets the value of the HasContextMenu attached property to a specified TextBox.
    /// </summary>
    /// <param name="element">The TextBox to which the attached property is written.</param>
    /// <param name="value">The needed HasContextMenu value.</param>
    public static void SetHasContextMenu(TextBox element, bool value)
    {
        if (element == null)
        {
            throw new ArgumentNullException("element");
        }
        element.SetValue(HasContextMenuProperty, value);
    }

    /// <summary>
    /// Identifies the HasContextMenu dependency property.
    /// </summary>
    public static readonly DependencyProperty HasContextMenuProperty =
        DependencyProperty.RegisterAttached(
            "HasContextMenu",
            typeof(bool),
            typeof(TextBox),
            new PropertyMetadata(false, OnHasContextMenuPropertyChanged));

    /// <summary>
    /// HasContextMenuProperty property changed handler.
    /// </summary>
    /// <param name="d">TextBoxContextMenu that changed its HasContextMenu.</param>
    /// <param name="e">Event arguments.</param>
    private static void OnHasContextMenuPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{ 
    // code
}

我应该补充说,附加的依赖属性是在一个继承自RadContextMenu的类中定义的,这是一个DependencyObject(我一直在阅读,并且某处建议如果附加属性在这样的类中定义,但这看起来很奇怪)

1 个答案:

答案 0 :(得分:0)

我明白了。这确实是由于在我所拥有的课程中定义了附加属性。

为了解决这个问题,我创建了一个名为TextBoxContextMenuService的新类,并将代码放在那里。