简体   繁体   中英

How to change dependency property behavior in UserControl

I have a WPF user control which contains a TextBox and some buttons. Now I want to change the way in which the VerticalContentAlignment property of the user control is handled in order to change only the vertical content alignment of the contained text box and not of the user control itself. So how can I override the VerticalContentAlignment dependency property of the user control in order to achieve my desired behavior?

You could write a ControlTemplate for the UserControl that simply ignores the VerticalContentAlignment property. Then bind the TextBox's VerticalAlignment to the VerticalContentAlignment property of the UserControl, eg by a RelativeSource Binding.

<UserControl ...>
    <UserControl.Template>
        <ControlTemplate TargetType="UserControl">
            <ContentPresenter
                HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"/>
        </ControlTemplate>
    </UserControl.Template>

    <Grid Background="AliceBlue">
        <TextBlock
            Text="Hello"
            VerticalAlignment="{Binding VerticalContentAlignment,
                RelativeSource={RelativeSource AncestorType=UserControl}}"/>
    </Grid>
</UserControl>

Test case:

<Grid>
    <local:MyUserControl
        Height="100" 
        VerticalAlignment="Center"
        VerticalContentAlignment="Bottom"/>
</Grid>

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