参考父控件的类型设置 DataTrigger 的样式
在我的窗口上有几个 GroupBox 控件,每个控件都包含一个网格控件。我想为这些网格指定一个样式。但仅限于那些直接位于 GroupBox 中的网格,所有其他网格不应受到影响。
我尝试了以下方法,但它不起作用,因为 GetType() 不是属性。
<Style TargetType="Grid">
<Style.Triggers>
<DataTrigger Binding="{Binding RelativeSource={RelativeSource Mode=Self}, Path=Parent.GetType()}" Value="{x:Type GroupBox}">
<!-- <Setter Property="..." Value="..."/> -->
</DataTrigger>
</Style.Triggers>
</Style>
我找到了一种解决方法,但这并不是一个真正完美的解决方案,因为我必须修改 GroupBoxes:
<Style TargetType="GroupBox">
<Setter Property="Tag" Value="blub"/>
</Style>
<Style TargetType="Grid">
<Style.Triggers>
<DataTrigger Binding="{Binding Path=Parent.Tag, RelativeSource={RelativeSource Mode=Self}}" Value="blub">
<!-- <Setter Property="..." Value="..."/> -->
</DataTrigger>
</Style.Triggers>
</Style>
显然我可以手动设置每个网格的样式,但我试图避免这种情况,因为它们有很多。我希望您能找到一种方法使第一个示例发挥作用。
On my Window there are several GroupBox Controls, each containing a Grid Control. To those Grids I want to asign a Style. But only to those Grids that are directly in a GroupBox, all other Grids should not be affected.
I have tried the following, which does not work as GetType() is no property.
<Style TargetType="Grid">
<Style.Triggers>
<DataTrigger Binding="{Binding RelativeSource={RelativeSource Mode=Self}, Path=Parent.GetType()}" Value="{x:Type GroupBox}">
<!-- <Setter Property="..." Value="..."/> -->
</DataTrigger>
</Style.Triggers>
</Style>
I have found a workaround, but it's not really a beautiful solution, as I have to modify the GroupBoxes:
<Style TargetType="GroupBox">
<Setter Property="Tag" Value="blub"/>
</Style>
<Style TargetType="Grid">
<Style.Triggers>
<DataTrigger Binding="{Binding Path=Parent.Tag, RelativeSource={RelativeSource Mode=Self}}" Value="blub">
<!-- <Setter Property="..." Value="..."/> -->
</DataTrigger>
</Style.Triggers>
</Style>
Obviously I could set the style for each Grid manually, but I'm trying to avoid that, as there are quite a lot of them. I hope you can find a way to make the first example work.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这段代码不起作用,因为Mode的类型实际上是BindingMode,它是一个Enumeration,并且它的成员都不是Self。所以这个赋值 Mode=Self 在你的代码中是错误的。要了解模式的可能值,单击此。
正确的编写方法是,
当然,为了使其工作,您必须保留已经编写的 GroupBox 样式。
This code would not work, because type of Mode is actually BindingMode which is an Enumeration, and none of it's member is Self. So this assignment Mode=Self is wrong in your code. To know the possible values of Mode, click this.
The correct way to write this is,
And of course, for this to work, you've to keep that Style for GroupBox which you've already written.
这对我有用:
它允许您根据父类型设置样式,而不必求助于标签,标签实际上应该由代码而不是标记使用。
This worked for me:
It allows you to set style based on parent type without having to resort to Tag which should really be used by code rather than by markup.
使用以下代码:
将 XAML 代码编写为:
Use following Code :
Write the XAML Code as :