Search code examples
avaloniauiavalonia

Avalonia How To Create Custom Popup


A little explanation first:

This is source code of Popup element

And this is example of using Popup DatePicker and it's xaml

I've tried use this example on empty window like this

Sample Code

Here is result:

enter image description here

So I want to create a OK/Cancel pick panel and use like DateTimePicker Pop and Select what do you want and accept or abort the selections.

How can I create a simple custom picker like this.


Solution

  • Edit: Here is My DateTimePicker and screenshots enter image description here

    After Tap

    enter image description here

    Ok I analyzed the existing codes for hours. Simply the answer is:

    Step 1: Create a presenter class for manage your controls and events for popup. (like DatePickerPresenter

    namespace AvaloniaTest.Views {
      public class SabriPresenter : PickerPresenterBase
      {
      ...
    
      }
    }
    

    Step 2: Create Template for this presenter in your window or resource.

    <Window xmlns="bla bla bla"
            xmlns:v="using:AvaloniaTest.Views"
            Title="AvaloniaTest">
    
      <Design.DataContext>
        <vm:MainWindowViewModel/>
      </Design.DataContext>
    
      <Window.Styles>
        <Style Selector="v|SabriPresenter" >
          <Setter Property="Template">
            <ControlTemplate>
              <Grid Background="AliceBlue">
                <Grid.ColumnDefinitions>
                  <ColumnDefinition Width="100"/>
                  <ColumnDefinition Width="100"/>
                </Grid.ColumnDefinitions>
                <Grid.RowDefinitions>
                  <RowDefinition Height="100"/>
                  <RowDefinition Height="20"/>
                </Grid.RowDefinitions>
                <Panel Grid.Column="0" Grid.Row="0" Grid.ColumnSpan="2">
                  <TextBlock Text="Your content..."/>
                </Panel>
                <Button Grid.Column="0" Grid.Row="0" Content="OK"/>
                <Button Grid.Column="1" Grid.Row="0" Content="Cancel"/>
              </Grid>
            </ControlTemplate>
          </Setter>
        </Style>
      </Window.Styles>
    </Window>
    

    Step 3: Use this presenter wherever you want

    <Window xmlns="bla bla"
            xmlns:v="using:AvaloniaTest.Views"
            >
      <StackPanel Orientation="Vertical" VerticalAlignment="Center">
        <TextBlock Text="{Binding Greeting}" HorizontalAlignment="Center" VerticalAlignment="Center"/>
        <Button Content="Popeye"  Name="sabri"/>
        <Popup Name="Popup"
               WindowManagerAddShadowHint="False"
               StaysOpen="False"
               PlacementMode="Bottom"
               PlacementTarget="{Binding ElementName=sabri}"
               >
          <v:SabriPresenter />
        </Popup>
      </StackPanel>
    </Window>
    

    Ta-daa! enter image description here