验证WPF Visual Tree

时间:2013-05-17 16:26:06

标签: c# wpf styles controltemplate

我试图强制要求添加的任何新样式都必须符合某些标准。这是一个简单的例子。

<Style TargetType="{x:Type CellValuePresenter}" BasedOn="{StaticResource {x:Type CellValuePresenter}}">
 <Setter Property="Tag" Value="1"></Setter>
  <Setter Property="Template">
    <Setter.Value>
      <ControlTemplate>
        <Border BorderThickness="{TemplateBinding BorderThickness}" />              
          ....
      </ControlTemplate>
    </Setter.Value>
  </Setter>
</Style>

更新

我试图从代码背后验证样式,如果样式有ControlTemplate,它的根应该是边框与BorderThickness模板绑定。

由于在呈现Control之前不会创建Visual Tree,因此我将在运行时根据目标类型创建控件并应用样式。我甚至尝试了以下方法 Appropriate way to force loading of a WPF Visual

我可以在WPF Tree Visualizer中看到可视树,但我无法使用LogicalTreeHelper.GetChildren完全导航

我正在试验各种想法:

    private void ValidateStyle(Style fieldStyle_, Field field_)
    {
      if (fieldStyle_.TargetType == typeof(CellValuePresenter))
      {
        StringBuilder sb = new StringBuilder();
        CellValuePresenter presenter = new CellValuePresenter();
        presenter.Style = fieldStyle_;

        if (fieldStyle_.Setters.Count > 0)
        {
          foreach (Setter setter in fieldStyle_.Setters)
          {
           if (setter.Property != null && setter.Property.PropertyType == typeof(ControlTemplate))
            {
              presenter.ApplyTemplate();
              ValidateColumnStyle(0, presenter);
            }
          }             
        }
      }
    }

    private void ValidateColumnStyle(int depth_, object obj_)
    {
      Debug.WriteLine(new string(' ', depth_) + obj_);
      if (!(obj_ is DependencyObject))
      {
        return;
      }

      if (obj_ is UIElement)
      {
        Viewbox vb = new Viewbox() {Child = obj_ as UIElement};
        vb.Measure(new Size(Double.PositiveInfinity, Double.PositiveInfinity));
        vb.Arrange(new Rect(vb.DesiredSize));
      }

      foreach (object child in LogicalTreeHelper.GetChildren(obj_ as DependencyObject))
        ValidateColumnStyle(depth_ + 1, child);
    }

我无法导航到Border元素,任何想法如何正确加载控件。

0 个答案:

没有答案