1

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

<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,则其根应该是 Border 与 BorderThickness 模板绑定。

由于在呈现控件之前不会创建可视树,因此我在运行时根据目标类型创建控件并应用样式。我什至尝试了以下 适当的方法来强制加载 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 元素,不知道如何正确加载控件。

4

0 回答 0