【问题标题】:Silverlight 4 - How to set Custom Attached Dependency property in Style?Silverlight 4 - 如何在样式中设置自定义附加依赖属性?
【发布时间】:2011-08-26 15:52:46
【问题描述】:

我的根 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(我一直在阅读并且在某处有人建议,如果附加属性是在这样一个类中定义,但这看起来很奇怪)

【问题讨论】:

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


    【解决方案1】:

    我想通了。这确实是由于在我的类中定义了附加属性。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-11
      • 2021-07-08
      • 1970-01-01
      • 1970-01-01
      • 2016-03-28
      • 1970-01-01
      相关资源
      最近更新 更多