【发布时间】:2011-09-22 18:45:05
【问题描述】:
我确信以前有人问过这个问题,但我没有很容易弄清楚如何表达这个查询。
我有这种风格;
<SolidColorBrush x:Key="SemiTransparentRedBrushKey">#F0FF0000</SolidColorBrush>
<Style x:Key="TextBoxEmptyError" TargetType="{x:Type TextBox}">
<Style.Triggers>
<DataTrigger Binding="{Binding RelativeSource={RelativeSource Self}, Path=Text.Length}" Value="0">
<Setter Property="BorderBrush" Value="{StaticResource ResourceKey=SemiTransparentRedBrushKey}"/>
</DataTrigger>
</Style.Triggers>
</Style>
当文本框为空时,我可以将其应用于文本框以具有红色边框。太好了,我可以将Style="{StaticResource TextBoxEmptyError}" 添加到控制标签中。但是,如果我想通过触发器应用这种样式,以便控件仅在某些条件下使用它(例如绑定为真),该怎么办?比如:
<TextBox.Style>
<Style TargetType="TextBox">
<Style.Triggers>
<DataTrigger Binding="{Binding Path=ApprovedRequired}" Value="True">
<Setter Property="Style" Value="{StaticResource TextBoxEmptyError}"></Setter>
</DataTrigger>
</Style.Triggers>
</Style>
尽管{"Style object is not allowed to affect the Style property of the object to which it applies."},此代码引发异常
这样的事情可以做吗?
编辑:如果样式触发器无法做到这一点,因为它会覆盖自身,是否有其他方法可以有条件地应用资源样式?
编辑:如果此操作有更合适的术语,我可以更改问题标题。
【问题讨论】:
-
你考虑过使用
Validation.ErrorTemplate吗?见:wpftutorial.net/DataValidation.html -
是的,但我确定这对于我正在使用的某些表单来说太过分了。这个问题的答案也将更适用于一般的样式使用,而不仅仅是我的红色错误边框。