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

9

我将尝试使用附加属性在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 : 找不到引用'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个回答

2
问题与Style的工作方式有关:基本上,在第一次引用时将创建一个Style的"副本",此时可能有多个TextBox控件需要应用此Style - 它会使用哪一个相对源?(被划掉的内容是原文作者自己否定了的观点)
(可能的)答案是使用Template而不是Style——使用控件或数据模板,您将能够访问TemplatedParent的可视树,这应该可以让您到达所需位置。
编辑:进一步思考后,我可能是错误的...当我回到电脑前时,我将组合一个快速测试工具并尝试证明/反驳这一点。
进一步编辑:虽然我最初说的可能是“正确”的,但这不是您的问题;Raul关于可视树的说法是正确的:
  • 您正在将TextBoxBackground属性设置为VisualBrush实例。
  • 该画笔的Visual未映射到控件的可视树中。
  • 因此,任何 {RelativeSource FindAncestor}导航都将失败,因为该可视元素的父级将为null。
  • 无论将其声明为Style还是ControlTemplate,这都是事实。
  • 尽管如此,依赖ElementName肯定是不理想的,因为它降低了定义的可重用性。
那怎么办呢?
昨晚我一直在绞尽脑汁,试图想出一种方法,在不成功的情况下,将适当的继承上下文传输到包含的画刷中...然而,我确实想出了这种超级hacky的方法:
首先是帮助属性(注意:我通常不会以这种方式编写代码,但试图节省空间):
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
问题在于VisualBrush内部的Label不是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>

这段代码应该可以正常工作。不需要更改其他代码,因此我不会重写所有的代码。

希望这个解决方案对你有用...


3
看起来这只是将元素名称硬编码到样式中,那么它怎么能够被重复使用呢?我只能使用这种解决方案创建一个文本框? - glasswall

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接