简体   繁体   中英

Return a value from a uwp usercontrol

A UWP UserControl with 2 buttons

public sealed partial class SaveChangesUserControl : UserControl
{
    public bool CanGo { get; set; }

    public SaveChangesUserControl()
    {
        InitializeComponent();
    }

    private void Leave(object sender, EventArgs e)
    {
        CanGo = true;
    }

    private void Stay(object sender, EventArgs e)
    {
        CanGo = false;
    }
}

SaveChangesUserControl will be in a xaml page. I can bind the visibility to a property in the xaml page. Leave and Stay are event handlers for buttons in SaveChangesUserControl . How do I capture CanGo as the return value of SaveChangesUserControl ?

Something like bool canGo = SaveChangesUserControl would be nice.

Like a ContentDialog , but not a ContentDialog

A UWP UserControl with 2 buttons

public sealed partial class SaveChangesUserControl : UserControl
{
    public bool CanGo { get; set; }

    public SaveChangesUserControl()
    {
        InitializeComponent();
    }

    private void Leave(object sender, EventArgs e)
    {
        CanGo = true;
    }

    private void Stay(object sender, EventArgs e)
    {
        CanGo = false;
    }
}

SaveChangesUserControl will be in a xaml page. I can bind the visibility to a property in the xaml page. Leave and Stay are event handlers for buttons in SaveChangesUserControl . How do I capture CanGo as the return value of SaveChangesUserControl ?

Something like bool canGo = SaveChangesUserControl would be nice.

Like a ContentDialog , but not a ContentDialog

You could use AutoResetEvent class to do a thread synchronization. When signaled, reset automatically after releasing a single waiting thread.

Please check the following code:

SaveChangesUserControl.xaml.cs

private static AutoResetEvent Locker = new AutoResetEvent(false);

public async Task<bool> ShowAsync()
{
    Visibility = Visibility.Visible;
    await Task.Run(() => {
        Locker.WaitOne();  //Wait a singal
    });
    return CanGo;
}
private void Leave(object sender, RoutedEventArgs e)
{
    Visibility = Visibility.Collapsed;
    CanGo = true;
    Locker.Set();  //Release a singal
}

private void Stay(object sender, RoutedEventArgs e)
{
    Visibility = Visibility.Collapsed;
    CanGo = false;
    Locker.Set();  //Release a singal
}

MainPage.xaml.cs

private async void Button_Click(object sender, RoutedEventArgs e)
{
    var t = await myUserControl.ShowAsync();  //Call the method, you could get a return value after you click on user control
}

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