简体   繁体   中英

Is there a way to automatically expose properties and events of a standard wpf control wrapped in a user control?

I wrapped a standard control as discussed here Quickest way to inherit a standard control in WPF?

in a user control. Now is there a way to automatically expose properties and events of a standard wpf control wrapped in a user control ? Could I use something like automatic Bubbling routing but how exactly ?

Otherwise I'll have to also create properties and events wrappers for my component that is cumbersome.

Yes, you have to provide new Dependency Properties on the user control to expose properties to the outside. As an example:

TimeframeSelector.xaml

<DatePicker SelectedDate="{Binding Path=StartDate, 
                            RelativeSource={RelativeSource Mode=FindAncestor, 
                              AncestorType={x:Type ctrl:TimeframeSelector}}}"/>

TimeframeSelector.xaml.cs

    public DateTime StartDate
    {
        get{ return (DateTime)GetValue(StartDateProperty);}
        set { SetValue(StartDateProperty, value); }
    }

    public static readonly DependencyProperty StartDateProperty =
        DependencyProperty.RegisterAttached(
        "StartDate", 
        typeof(DateTime), 
        typeof(TimeframeSelector), 
        new FrameworkPropertyMetadata(
            DateTime.MinValue,
            FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));

You need to use the RelativeSource binding as you won't find the DP in the visual tree otherwise. If you are using Visual Studio, there is template named propdp which you can use to create depedendency properties very fast.

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