我正在为基本属性网格创建一些样式。例如,XAML 将是
<StackPanel Style="{StaticResource propertyGrid}" Orientation="Vertical" >
<ItemsControl Tag="property">
<Label>Nodes</Label>
<TextBox Text="{Binding Nodes}"/>
</ItemsControl>
<ItemsControl Tag="property">
<Label >Major Diameter</Label>
<TextBox Text="{Binding MajorDiameter}"/>
</ItemsControl>
<ItemsControl Tag="property">
<Label>Minor Diameter</Label>
<TextBox Text="{Binding MinorDiameter}"/>
</ItemsControl>
<ItemsControl Tag="property">
<Label>Excenter</Label>
<TextBox Text="{Binding Excenter}"> </TextBox>
</ItemsControl>
</StackPanel>
我的造型遵循这个逻辑。带有 Tag 的 ItemsControl 中的标签或文本框property
获得特殊样式。如果我是作为伪 CSS 做的,我会写
ItemsControl.property Label {
Grid.Row: 0;
FontWeight: bold;
Padding:0,4,0,0;
}
ItemsControl.property TextBox {
Grid.Row: 1;
FontWeight: bold;
}
在咬牙切齿之后,我想出了一种方法来做到这一点,那就是使用 DataTriggers 来回顾树,而不是使用 CSS 心态去往下看树。然而,我对它的冗长感到相当震惊。见下文。
<Style TargetType="StackPanel" x:Key="propertyGrid">
<Style.Resources>
<Style TargetType="Label">
<Style.Triggers>
<DataTrigger Binding="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ItemsControl}}, Path=Tag}" Value="property">
<Setter Property="Grid.Row" Value="0"/>
<Setter Property="FontWeight" Value="Bold"/>
<Setter Property="Padding" Value="0,4,0,0"/>
</DataTrigger>
</Style.Triggers>
</Style>
<Style TargetType="TextBox">
<Style.Triggers>
<DataTrigger Binding="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ItemsControl}}, Path=Tag}" Value="property">
<Setter Property="FontWeight" Value="Bold"/>
<Setter Property="Grid.Row" Value="1"/>
</DataTrigger>
</Style.Triggers>
</Style>
<Style TargetType="ItemsControl" x:Key="property">
<Style.Triggers>
<Trigger Property="Tag" Value="property">
<Setter Property="Focusable" Value="False"/>
<Setter Property="ItemsPanel">
<Setter.Value>
<ItemsPanelTemplate>
<Grid Width="Auto">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="40*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
</Grid>
</ItemsPanelTemplate>
</Setter.Value>
</Setter>
</Trigger>
</Style.Triggers>
</Style>
</Style.Resources>
</Style>
我的问题是。这样做有捷径或更好的符号吗?我很想写一个 WPFCSS 编译器来处理这个;)我可以写一个 MarkupExtension 来清理它。如果可能的话,我希望任何解决方案也能在设计时工作。
例如,是否可以编写一个扩展,例如
<AncestorTrigger TargetType="ItemsControl" Path="Tag" Value="property">
<Setter Property="Grid.Row" Value="0"/>
<Setter Property="FontWeight" Value="Bold"/>
<Setter Property="Padding" Value="0,4,0,0"/>
</AncestorTrigger>
? 这比记住如何写要容易得多
<DataTrigger Binding="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ItemsControl}}, Path=Tag}" Value="property">