简体   繁体   中英

Why can't I attach ToggleButton.IsChecked property to an Expander

We can attach DockPanel.Dock to an Expander but we can't attach ToggleButton.IsChecked. Why?

<Expander DockPanel.Dock='Bottom'> <!--Compile-->
<Expander ToggleButton.IsChecked='True'> <!--Doesn't compile-->

I found the answer in the source:

From ToggleButton :

public static readonly DependencyProperty IsCheckedProperty =
            DependencyProperty.Register(
                    "IsChecked",
                    typeof(bool?),
                    typeof(ToggleButton),
                    new FrameworkPropertyMetadata(
                            BooleanBoxes.FalseBox,
                            FrameworkPropertyMetadataOptions.BindsTwoWayByDefault | FrameworkPropertyMetadataOptions.Journal,
                            new PropertyChangedCallback(OnIsCheckedChanged)));

Form DockPanel :

public static readonly DependencyProperty DockProperty =
            DependencyProperty.RegisterAttached(
                    "Dock", 
                    typeof(Dock), 
                    typeof(DockPanel),
                    new FrameworkPropertyMetadata(
                        Dock.Left, 
                        new PropertyChangedCallback(OnDockChanged)),
                    new ValidateValueCallback(IsValidDock));

Dock is registered with RegisterAttached method instead of Register .

IsChecked is not an attachable property. If you are looking to bind a ToggleButton and a Expander you can do the following:

<ToggleButton x:Name="toggle" IsChecked="True" />
<Expander IsExpanded="{Binding ElementName=toggle, Path=IsChecked}" />

Both are dependency properties but, as you pointed out, one is Register and one is RegisterAttached. That's the difference and why IsChecked can't be exposed onto other controls. See the different answers (especially Haris Hasan's) in this SO Post. for a better explanation of the differences between the two registration methods.

As per your comment above, if you just want a CheckBox to be added to the Expander (the Header) in addition to the ToggleButton that already exists then simply do this:

 <Expander>
    <Expander.Header>
        <CheckBox VerticalAlignment="Center" IsChecked="{Binding MyBooleanPropertySomewhere, Mode=TwoWay}"/>
    </Expander.Header>
</Expander>

Then there is no reason to have it exposed on the Expander - you can set or bind IsChecked right there.

Hope this helped some.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM