如何绑定到Style.Resource中的附加属性?

时间:2012-11-29 17:36:44

标签: c# .net wpf xaml

我正在尝试使用附加属性在TextBox的背景中创建提示文本标签,但我无法解析样式资源中文本标题的绑定:

样式定义:

<Style x:Key="CueBannerTextBoxStyle"
       TargetType="TextBox">
  <Style.Resources>
    <VisualBrush x:Key="CueBannerBrush"
                 AlignmentX="Left"
                 AlignmentY="Center"
                 Stretch="None">
      <VisualBrush.Visual>
        <Label Content="{Binding Path=(EnhancedControls:CueBannerTextBox.Caption), RelativeSource={RelativeSource AncestorType={x:Type TextBox}}}"
               Foreground="LightGray"
               Background="White"
               Width="200" />
      </VisualBrush.Visual>
    </VisualBrush>
  </Style.Resources>
  <Style.Triggers>
    <Trigger Property="Text"
             Value="{x:Static sys:String.Empty}">
      <Setter Property="Background"
              Value="{DynamicResource CueBannerBrush}" />
    </Trigger>
    <Trigger Property="Text"
             Value="{x:Null}">
      <Setter Property="Background"
              Value="{DynamicResource CueBannerBrush}" />
    </Trigger>
    <Trigger Property="IsKeyboardFocused"
             Value="True">
      <Setter Property="Background"
              Value="White" />
    </Trigger>
  </Style.Triggers>
</Style>

附属物:

    public class CueBannerTextBox
{
    public static String GetCaption(DependencyObject obj)
    {
        return (String)obj.GetValue(CaptionProperty);
    }

    public static void SetCaption(DependencyObject obj, String value)
    {
        obj.SetValue(CaptionProperty, value);
    }

    public static readonly DependencyProperty CaptionProperty =
        DependencyProperty.RegisterAttached("Caption", typeof(String), typeof(CueBannerTextBox), new UIPropertyMetadata(null));
}

用法:

<TextBox x:Name="txtProductInterfaceStorageId" 
                 EnhancedControls:CueBannerTextBox.Caption="myCustomCaption"
                 Width="200" 
                 Margin="5" 
                 Style="{StaticResource CueBannerTextBoxStyle}" />

您的想法是,您可以在创建文本框时定义可视画笔中使用的文本提示,但我收到了绑定错误:

System.Windows.Data Error: 4 : Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='System.Windows.Controls.TextBox', AncestorLevel='1''. BindingExpression:Path=(0); DataItem=null; target element is 'Label' (Name=''); target property is 'Content' (type 'Object')

如果我只是对样式中的Label.Content属性进行硬编码,则代码可以正常工作。

有什么想法吗?

2 个答案:

答案 0 :(得分:2)

这里的问题与Style的工作方式有关:基本上,Style的一个“副本”将被创建(在第一次引用时),此时,那里可能是您希望应用TextBox的多个Style控件 - 它将用于RelativeSource吗?

(可能)答案是使用Template代替Style - 使用控件或数据模板,您将能够访问可视化树TemplatedParent的{​​{1}},这应该是你需要的地方。

编辑:进一步思考,我可能在这里不正确......当我回到计算机前时,我会把快速测试工具放在一起,看看我是否可以证明/反驳这一点。

进一步编辑:虽然我最初所说的可以说是“真实的”,但这不是你的问题;劳尔说的是:视觉树是正确的:

  • 您要将Background上的TextBox属性设置为VisualBrush个实例。
  • 该画笔的Visual 映射到控件的Visual Tree中。
  • 因此,任何 {RelativeSource FindAncestor}导航都会失败,因为该视觉的父级将为null。
  • 无论是宣布为Style还是ControlTemplate,都属于这种情况。
  • 所有这一切,依赖于ElementName肯定是不理想的,因为它降低了定义的可重用性。

那么,该怎么办?

我一直在捣乱我的大脑,试图想出一种方法来调整适当的继承背景,并没有成功......我确实拿出了这个超级hacky 然而,方式:

首先,helper属性(注意:我通常不会以这种方式设置代码,但试图节省空间):

public class HackyMess 
{
    public static String GetCaption(DependencyObject obj)
    {
        return (String)obj.GetValue(CaptionProperty);
    }

    public static void SetCaption(DependencyObject obj, String value)
    {
        Debug.WriteLine("obj '{0}' setting caption to '{1}'", obj, value);
        obj.SetValue(CaptionProperty, value);
    }

    public static readonly DependencyProperty CaptionProperty =
        DependencyProperty.RegisterAttached("Caption", typeof(String), typeof(HackyMess),
            new FrameworkPropertyMetadata(null));

    public static object GetContext(DependencyObject obj) { return obj.GetValue(ContextProperty); }
    public static void SetContext(DependencyObject obj, object value) { obj.SetValue(ContextProperty, value); }

    public static void SetBackground(DependencyObject obj, Brush value) { obj.SetValue(BackgroundProperty, value); }
    public static Brush GetBackground(DependencyObject obj) { return (Brush) obj.GetValue(BackgroundProperty); }

    public static readonly DependencyProperty ContextProperty = DependencyProperty.RegisterAttached(
        "Context", typeof(object), typeof(HackyMess),
        new FrameworkPropertyMetadata(default(HackyMess), FrameworkPropertyMetadataOptions.OverridesInheritanceBehavior | FrameworkPropertyMetadataOptions.Inherits));
    public static readonly DependencyProperty BackgroundProperty = DependencyProperty.RegisterAttached(
        "Background", typeof(Brush), typeof(HackyMess),
        new UIPropertyMetadata(default(Brush), OnBackgroundChanged));

    private static void OnBackgroundChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
    {
        var rawValue = args.NewValue;
        if (rawValue is Brush)
        {
            var brush = rawValue as Brush;
            var previousContext = obj.GetValue(ContextProperty);
            if (previousContext != null && previousContext != DependencyProperty.UnsetValue)
            {
                if (brush is VisualBrush)
                {
                    // If our hosted visual is a framework element, set it's data context to our inherited one
                    var currentVisual = (brush as VisualBrush).GetValue(VisualBrush.VisualProperty);
                    if(currentVisual is FrameworkElement)
                    {
                        (currentVisual as FrameworkElement).SetValue(FrameworkElement.DataContextProperty, previousContext);
                    }
                }
            }
            // Why can't there be just *one* background property? *sigh*
            if (obj is TextBlock) { obj.SetValue(TextBlock.BackgroundProperty, brush); }
            else if (obj is Control) { obj.SetValue(Control.BackgroundProperty, brush); }
            else if (obj is Panel) { obj.SetValue(Panel.BackgroundProperty, brush); }
            else if (obj is Border) { obj.SetValue(Border.BackgroundProperty, brush); }
        }
    }
}

现在更新的XAML:

<Style x:Key="CueBannerTextBoxStyle"
       TargetType="{x:Type TextBox}">
  <Style.Triggers>
    <Trigger Property="TextBox.Text"
             Value="{x:Static sys:String.Empty}">
      <Setter Property="local:HackyMess.Background">
        <Setter.Value>
          <VisualBrush AlignmentX="Left"
                       AlignmentY="Center"
                       Stretch="None">
            <VisualBrush.Visual>
              <Label Content="{Binding Path=(local:HackyMess.Caption)}"
                     Foreground="LightGray"
                     Background="White"
                     Width="200" />
            </VisualBrush.Visual>
          </VisualBrush>
        </Setter.Value>
      </Setter>
    </Trigger>
    <Trigger Property="IsKeyboardFocused"
             Value="True">
      <Setter Property="local:HackyMess.Background"
              Value="White" />
    </Trigger>
  </Style.Triggers>
</Style>
<TextBox x:Name="txtProductInterfaceStorageId"
         local:HackyMess.Caption="myCustomCaption"
         local:HackyMess.Context="{Binding RelativeSource={RelativeSource Self}}"
         Width="200"
         Margin="5"
         Style="{StaticResource CueBannerTextBoxStyle}" />
<TextBox x:Name="txtProductInterfaceStorageId2"
         local:HackyMess.Caption="myCustomCaption2"
         local:HackyMess.Context="{Binding RelativeSource={RelativeSource Self}}"
         Width="200"
         Margin="5"
         Style="{StaticResource CueBannerTextBoxStyle}" />

答案 1 :(得分:2)

问题是Label内的VisualBrush不是TextBox的视觉子项,这就是绑定不起作用的原因。我对该问题的解决方案是使用ElementName绑定。但是您创建的可视化画笔位于Style的字典资源中,然后ElementName绑定将无效,因为找不到元素ID。解决方案是在全局字典资源中创建VisualBrush。请参阅此XAML代码以了解VisualBrush

<Window.Resources>
  <VisualBrush x:Key="CueBannerBrush"
               AlignmentX="Left"
               AlignmentY="Center"
               Stretch="None">
    <VisualBrush.Visual>
      <Label Content="{Binding Path=(EnhancedControls:CueBannerTextBox.Caption), ElementName=txtProductInterfaceStorageId}"
             Foreground="#4F48DD"
             Background="#B72121"
             Width="200"
             Height="200" />
    </VisualBrush.Visual>
  </VisualBrush>
  <Style x:Key="CueBannerTextBoxStyle"
         TargetType="{x:Type TextBox}">
    <Style.Triggers>
      <Trigger Property="Text"
               Value="{x:Static System:String.Empty}">
        <Setter Property="Background"
                Value="{DynamicResource CueBannerBrush}" />
      </Trigger>
      <Trigger Property="Text"
               Value="{x:Null}">
        <Setter Property="Background"
                Value="{DynamicResource CueBannerBrush}" />
      </Trigger>
      <Trigger Property="IsKeyboardFocused"
               Value="True">
        <Setter Property="Background"
                Value="White" />
      </Trigger>
    </Style.Triggers>
  </Style>
</Window.Resources>

此代码应该有效。不需要更改代码,所以我不会重写所有代码。

希望这个解决方案适合你...