Floating custom touch control in WPF

2019-08-11 03:40发布

问题:

I am trying to create a floating control in WPF that can receive touch events. I searched a lot and the only solution for a floating control I found was the Popup control. Problem: The Popup control cannot receive touch events. And since I am using a SurfaceListBox inside my Popup, I need touch events. I tried to make the popup receive touch events via the following:

TouchExtensions.EnableSurfaceInput((HwndSource)HwndSource.FromVisual(this.selectionListPopup));

but it didn't have any effect. Is there any way to make popups receive touches? Is there any other control or way that could be used?

My end goal is to have a control that is floating above other controls - that means it is not clipped or obscured by other controls.

Here is the XAML I used so far:

<Popup Name="selectionListPopup"
        PlacementTarget="{Binding ElementName=selectedItemButton}"
        Placement="Relative"
        VerticalOffset="{Binding ElementName=this, Path=SelectionListTop}"
        HorizontalOffset="{Binding ElementName=this, Path=SelectionListLeft}"
        IsOpen="{Binding ElementName=this, Path=IsSelecting, Mode=TwoWay}"
        StaysOpen="False"
        AllowsTransparency="True" 
        Focusable="False">
        <s:SurfaceListBox Name="selectionList"
                          ItemsSource="{Binding ElementName=this, Path=ItemsSource}"
                          SelectedItem="{Binding ElementName=this, Path=SelectedItem, Mode=TwoWay}"
                          SelectionChanged="OnSelectionListSelectionChanged">
        </s:SurfaceListBox>
</Popup>

回答1:

It's not the HwndSource of the Popup, but the HwndSource of the visual parent of the Popup.Child. Sounds strange, I know.

So in the Opened-event of my popup I call the following code:

var myPopup = sender as Popup;

HwndSource hwndSource = (HwndSource)PresentationSource.FromVisual((Visual)VisualTreeHelper.GetParent(myPopup.Child)); 

hwndSource.EnableSurfaceInput();