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

夙愿已清 提交于 2020-01-06 12:14:29

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/4773542/is-there-a-way-to-automatically-expose-properties-and-events-of-a-standard-wpf-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!