Search code examples
wpfbuttonbindingstackpanelisenabled

Binding Button IsEnabled to StackPanel has Children


I'm wondering if I can bind my Button isEnabled to my StackPanel Children (has children). If the stackpanel has children, then my button is enabled, no children my button is disabled. Currently I just handle this in code, but I started wondering if this was something I could bind. Thanks for any thoughts...


Solution

  • Actually since you deal with a bool you can invert the logic and do it without converters:

    <StackPanel Name="sp" />
    <Button Content="A Button">
        <Button.Style>
            <Style TargetType="{x:Type Button}">
                <Style.Triggers>
                    <DataTrigger Binding="{Binding ElementName=sp, Path=Children.Count}" Value="0">
                        <Setter Property="IsEnabled" Value="False"/>
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </Button.Style>
    </Button>
    

    Using this you run into some problems in terms of getting updates since Children.Count is not a DP, you can use an ItemsControl though to get around that (it pretty much behaves like a StackPanel by default):

    <ItemsControl Name="ic" />
    <Button Content="A Button">
        <Button.Style>
            <Style TargetType="{x:Type Button}">
                <Style.Triggers>
                    <DataTrigger Binding="{Binding ElementName=ic, Path=Items.Count}" Value="0">
                        <Setter Property="IsEnabled" Value="False"/>
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </Button.Style>
    </Button>