【问题标题】:Can I apply a certain style for results from validation to only one button?我可以将验证结果的某种样式应用到一个按钮吗?
【发布时间】:2017-01-31 09:37:05
【问题描述】:

我正在开发一个 WPF 应用程序,在该应用程序中我使用 IDataErrorInfo 和验证规则进行验证。 为了在运行时显示验证结果,我在窗口的 XAML 中创建了一些样式。 只要有输入错误,其中一种样式应该禁用保存按钮:

<Window.Resources>
    <!--Disabling the Save-button by style not viewmodel-property-->
    <Style TargetType="{x:Type Button}">
        <Style.Triggers>
            <DataTrigger Binding="{Binding ElementName=tbx_firstname, Path=(Validation.HasError)}" Value="true">
                <Setter Property="IsEnabled" Value="False"/>
            </DataTrigger>
            <DataTrigger Binding="{Binding ElementName=tbx_lastname, Path=(Validation.HasError)}" Value="true">
                <Setter Property="IsEnabled" Value="False"/>
            </DataTrigger>
            <DataTrigger Binding="{Binding ElementName=tbx_age, Path=(Validation.HasError)}" Value="true">
                <Setter Property="IsEnabled" Value="False"/>
            </DataTrigger>
        </Style.Triggers>
    </Style>
</Window.Resources>

我有两个问题:

  1. 该样式禁用窗口上的所有按钮。我该怎么做才能只禁用保存按钮? 我尝试了以下方法,但似乎存在语法错误(VS 不接受):

    <Style TargetType="{x:Name btn_save}">
    
  2. 在保存按钮的样式中,我必须检查每个经过验证的控件。 是否有另一种可能使该部分更短且不易出错(因为它必须与视图模型结合)?

提前致谢!

【问题讨论】:

    标签: wpf validation xaml idataerrorinfo


    【解决方案1】:

    如果您希望将样式应用于单个按钮而不是所有按钮,则需要为样式分配一个键,例如:

    <Style x:Key="SaveButtonStyle" TargetType="{x:Type Button}">
    

    这样它就不会隐式应用于所有按钮。要将其应用到您的保存按钮,请明确指定按钮的样式:

    <Button Style="{StaticResource SaveButtonStyle}">
    

    【讨论】:

    • 非常感谢曼弗雷德!我在一分钟前发现了同样的情况。只需一个小钥匙就能产生如此大的不同。
    猜你喜欢
    • 2020-09-22
    • 2011-01-27
    • 2018-06-22
    • 2011-01-27
    • 2020-02-22
    • 2015-07-05
    • 1970-01-01
    • 1970-01-01
    • 2016-05-01
    相关资源
    最近更新 更多