如何将参数添加到现有样式

时间:2015-12-03 13:27:47

标签: c# wpf

我的XAML中有以下按钮:

<Button Content="ADD"
        Style="{DynamicResource MaterialDesignFlatButton}" />

我想保留样式并为其创建验证规则,就好像某个文本框为空它应该禁用该按钮并在其上设置工具提示。

所以我尝试了这个:

<Button Content="ADD"
        Command="{Binding AddDateCommand}"
        VerticalAlignment="Top"
        Margin="8 0 0 0">
    <Button.Style>
        <Style BasedOn="{StaticResource MaterialDesignFlatButton}">
             <triggers to check the rules and set the attributes/>
        </Style>
    </Button.Style>
</Button>

但我收到以下错误:

  

只能基于具有基本类型的目标类型的Style   &#39; IFrameworkInputElement&#39;

2 个答案:

答案 0 :(得分:1)

如果您有一个IsEnabled

,请使用该按钮的TextBox属性
<Button Content="ADD"
    Command="{Binding AddDateCommand}"
    VerticalAlignment="Top"
    Margin="8 0 0 0"
    IsEnabled="{Binding ElementName=yourTxtBox, Path=Text.Length, Mode=OneWay}" />

但对于两个TextBoxes,你应该使用:

<Button.Style>
      <Style TargetType="{x:Type Button}">
          <Style.Triggers>
              <MultiDataTrigger>
                     <MultiDataTrigger.Conditions>
                        <Condition Binding="{Binding ElementName=firstTxtBox, Path=Text.Length, Mode=OneWay}" Value="0"/>
                        <Condition Binding="{Binding ElementName=lastTxtBox, Path=Text.Length, Mode=OneWay}" Value="0"/>
                    </MultiDataTrigger.Conditions>
                    <Setter Property="IsEnabled" Value="False"/>
             </MultiDataTrigger>
         </Style.Triggers>
      </Style>
</Button.Style>

答案 1 :(得分:1)

  1. 您现在的代码中会出现错误:样式只能设置一次

  2. 您必须将TargetType与BasedOn样式一起使用。

  3. 所以,定义你的风格应该在概念上如下:

    <Style x:Key="MaterialDesignFlatButton" TargetType="Button">
       <Setter Property="Background" Value="Red"/>
    </Style>
    
    <Style x:Key="NewStyle" BasedOn="{StaticResource MaterialDesignFlatButton}" 
           TargetType="Button">
        <Style.Triggers>
             <MultiDataTrigger>
                <MultiDataTrigger.Conditions>
                    <Condition Binding="{Binding ElementName=tb, Path=Text.Length, Mode=OneWay}" Value="10"/>
                </MultiDataTrigger.Conditions>
                <Setter Property="IsEnabled" Value="True"/>
             </MultiDataTrigger>
        </Style.Triggers>
        <Setter Property="BorderBrush" Value="Cornsilk"/>
        <Setter Property="BorderThickness" Value="15"/>
        <Setter Property="Foreground" Value="MediumPurple"/>
        <Setter Property="FontSize" Value="15"/>
    </Style>