rbasniak
rbasniak

Reputation: 4964

How to add parameters to an existing style

I have the following button in my XAML:

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

I would like to keep the style and create a validation rule for it, like if some textbox is empty it should disable the button and set a tooltip on it.

So I tried this:

<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>

But I'm getting the following error:

Can only base on a Style with target type that is base type 'IFrameworkInputElement'

Upvotes: 0

Views: 266

Answers (2)

AnjumSKhan
AnjumSKhan

Reputation: 9827

  1. You will get an error : Style can be set only once in your present code.

  2. You have to use TargetType with BasedOn styles.

So, define your style should be conceptually like this :

<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>

Upvotes: 1

Salah Akbari
Salah Akbari

Reputation: 39956

use IsEnabled property of the button if you have one TextBox:

<Button Content="ADD"
    Command="{Binding AddDateCommand}"
    VerticalAlignment="Top"
    Margin="8 0 0 0"
    IsEnabled="{Binding ElementName=yourTxtBox, Path=Text.Length, Mode=OneWay}" />

But for two TextBoxes you should use:

<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>

Upvotes: 1

Related Questions