开发者

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.开发者_StackOverflow Currently I just handle this in code, but I started wondering if this was something I could bind. Thanks for any thoughts...


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>


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜