Brian Triplett
Brian Triplett

Reputation: 3532

Set Width in WPF with DataTrigger

I have a border which contains other items (StackPanel with buttons). I'm using a DataTrigger to try to shrink down the border when a "IsHidden" property is toggled to true. I'm confident that the bindings are correct and the property in the DataContext is changing and the UI is being notified. The problem is the Width property is just not being set.

Any ideas?

<Border Width="200" Background="{StaticResource BasicBrush}" Padding="0"
        BorderBrush="{StaticResource MainBrush}" BorderThickness="0 10 10 0">
    <Border.Style>
        <Style TargetType="{x:Type Border}">
            <Style.Triggers>
                <DataTrigger Binding="{Binding IsHidden}" Value="True">
                    <Setter Property="Width" Value="50"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Border.Style>
</Border>

Upvotes: 0

Views: 2307

Answers (2)

Brian Triplett
Brian Triplett

Reputation: 3532

Found the answer here. It had to do with Style precedence. I needed to move the setting of Width out of the Border element and into the style setter like below.

<Border Background="{StaticResource BasicBrush}" Padding="0"
        BorderBrush="{StaticResource MainBrush}" BorderThickness="0 10 10 0">
    <Border.Style>
        <Style TargetType="{x:Type Border}">
            <Setter Property="Width" Value="200"/>
            <Style.Triggers>
                <DataTrigger Binding="{Binding IsHidden}" Value="True">
                    <Setter Property="Width" Value="50"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Border.Style>
</Border>

Upvotes: 0

Rohit Vats
Rohit Vats

Reputation: 81243

Move the property inside style setter and it will work fine. Local value has higher precedence order over style triggers. So, any change in property from Style triggers won't change local value.

<Style>
  <Setter Property="Width" Value="200"/>
  <Style.Triggers>
    .....
  </Style.Triggers>
</Style>

You can read more about it here - Dependency Property Value Precedence.

Upvotes: 3

Related Questions