How to bring a Control to view though it is not in VisualTree

89 Views Asked by At

I am Sorry for the stupid title, but my requirement is quite similar to that.

I have a CustomControl extended from DatePicker. I dont have any separate Control Structure for this. I need to attach a Popup to its Structure. So what am doing is in the Constructor of my custom control, initializing a new popup with the placement target as my custom control.

Here i know that this popup will not be in the Visual Tree. I need to bring this popup to view when a button clicks..

Sorry for my bad English. Hope the question is clear...

Thanks

1

There are 1 best solutions below

2
On

If I understand your question correctly, you want to show or hide popup that is defined in your Custom Control whenever some other button is clicked.

To achieve that you could add a Dependency Property to your custom control and set IsOpen property on Popup accordingly.

Sample Code below:

public static readonly DependencyProperty IsPopupOpenProperty =
    DependencyProperty.Register("IsPopupOpen", typeof (bool), typeof (CustomDatePicker), new PropertyMetadata(default(bool), PropertyChangedCallback));

public bool IsPopupOpen
{
    get { return (bool) GetValue(IsPopupOpenProperty); }
    set { SetValue(IsPopupOpenProperty, value); }
}

static void PropertyChangedCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs)
{
    var datePicker = (CustomDatePicker) dependencyObject;
    datePicker.ShowOrHidePopup();
}

void ShowOrHidePopup()
{
    _popup.IsOpen = IsPopupOpen;
}

You can then show/hide popup by setting IsPopupOpen property on your custom control. Since, IsPopupOpen a dependency property, you could also set this property via Data Binding.

Hope this helps or gives you some idea in approaching your problem!

UPDATE

My XAML

<StackPanel Orientation="Vertical">
        <Button Click="ButtonBase_OnClick" Content="Click Me!!" Margin="10" />
        <local:CustomDatePicker x:Name="customDatePicker" />
</StackPanel>

My XAML.cs

void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
    customDatePicker.IsPopupOpen = !customDatePicker.IsPopupOpen;
}