【问题标题】:WPF The ControlTemplate I use for the Validation.ErrorTemplate cannot access the parent ControlWPF 我用于 Validation.ErrorTemplate 的 ControlTemplate 无法访问父控件
【发布时间】:2013-02-21 19:09:31
【问题描述】:

当我的自定义 ComboBox 出现验证错误时,我正在尝试设置它的边距。 这是我尝试使用的代码:

<ComboBox x:Class="Emsc.Prestige.Windows.AutoCompleteComboBox"
          xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
          xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
          x:Name="MyComboBox">

    <Validation.ErrorTemplate>
        <ControlTemplate>
            <Border x:Name="ErrorBorder" BorderThickness="2" CornerRadius="2">
                <AdornerElementPlaceholder x:Name="adorner"/>
            </Border>
        <ControlTemplate.Triggers>
            <DataTrigger Binding="{Binding Path=AdornedElement.(Validation.Errors)[0].ErrorContent, ElementName=adorner, Converter={StaticResource ErrorContentToErrorTypeConverter}}"
                                                        Value="Critical">
                <Setter TargetName="ErrorBorder" Property="BorderBrush" Value="Red" />
                <Setter TargetName="MyComboBox" Property="Margin" Value="0,0,10,0" />
            </DataTrigger>
        </ControlTemplate>
    </Validation.ErrorTemplate>
</ComboBox>

所以当我为 ErrorBorder 元素设置 BorderBrush 时,它工作正常。但是当我尝试访问 MyComboBox 的 Margin 属性(或任何属性)时,出现以下错误:

属性“TargetName”不代表有效的目标 “Setter”,因为找不到名为“MyComboBox”的元素。制作 确保在任何 Setter、Trigger 或 使用它的条件。

我想在 XAML 中而不是在后面的代码中访问 MyComboBox 的边距。 有没有办法通过我的 DataTrigger 中的 Setter 访问“TemplatedParent”?

【问题讨论】:

    标签: wpf controltemplate


    【解决方案1】:

    尝试使用样式元素,像这样

    <Style TargetType="ComboBox">
      <Style.Triggers>
        <Trigger Property="Validation.HasError" Value="True">
          <Setter Property="Margin" Value="2" />
        </Trigger>
      </Style.Triggers>
    </Style>
    

    将此样式应用于您的组合框

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-10-23
      • 1970-01-01
      • 1970-01-01
      • 2013-10-07
      • 1970-01-01
      • 1970-01-01
      • 2013-11-03
      相关资源
      最近更新 更多