Question

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

Was it helpful?

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>

OTHER TIPS

You could write a simple ValueConverter which does that logic for you. Bind the IsEnabled of the Button to the StackPanel and in your value converter check if it has any children and then return true/false.

A simpler solution (requires no ItemsPanel) than H.B.'s might be binding to the ActualHeight property of the StackPanel, since its size will be 0 if no children are present.

<Style.Triggers>
  <DataTrigger Binding="{Binding ElementName=sp, Path=ActualHeight}" Value="0">
    <Setter Property="IsEnabled" Value="False"/>
  </DataTrigger>
</Style.Triggers>

You may have to use VerticalAlignment="Top" for the StackPanel if it does not shrink properly.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top