簡體   English   中英

為什么我不能將ToggleButton.IsChecked屬性附加到擴展器

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

我們可以將DockPanel.Dock附加到Expander,但是不能附加ToggleButton.IsChecked。 為什么?

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

我在源代碼中找到了答案:

ToggleButton

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

表格DockPanel

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

Dock是使用RegisterAttached方法而不是Register

IsChecked不是可附加屬性。 如果要綁定ToggleButton和Expander,可以執行以下操作:

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

兩者都是依賴項屬性,但是,正如您所指出的,一個是Register,另一個是RegisterAttached。 這就是區別,為什么不能將IsChecked公開給其他控件。 在此SO Post中查看不同的答案(尤其是Haris Hasan的答案) 以便更好地解釋這兩種注冊方法之間的差異。

根據上面的評論,如果您只想將CheckBox除了已經存在的ToggleButton之外添加到Expander(標題)中,則只需執行以下操作:

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

這樣就沒有理由在Expander上公開它了-您可以在此處設置或綁定IsChecked。

希望這對一些人有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM