【问题标题】:Return a value from a uwp usercontrol从 uwp 用户控件返回一个值
【发布时间】:2021-05-17 10:41:31
【问题描述】:

带有 2 个按钮的 UWP UserControl

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 将在 xaml 页面中。我可以将可见性绑定到 xaml 页面中的属性。 LeaveStaySaveChangesUserControl 中按钮的事件处理程序。如何捕获CanGo 作为SaveChangesUserControl 的返回值?

像 bool canGo = SaveChangesUserControl 这样的东西会很好。

类似于ContentDialog,但不是ContentDialog

【问题讨论】:

  • 我对你的目的有点困惑。方法 Leave()Stay() Button.Click 是事件处理程序吗? SaveChangesUserControlVisibility属性的数据绑定源是位于SaveChangesUserControl实例还是MainPage实例?我想知道你是否想在离开SaveChangesUserControl 实例时获得CanGo 的值,就像ContentDialog 的ShowAsync() 一样。
  • @YanGu-MSFT Leave() 和 Stay() 是 Button.Click 事件处理程序。我希望返回 CanGo 之类的东西 bool canGo=new SaveChangedUserControl();
  • 构造函数将返回一个 SaveChangedUserControl 实例,而不是任何其他类型的值。您可以从 SaveChangedUserControl 的实例中获取 CanGo 的值,这是否符合您的要求? CanGo 是 SaveChangedUserControl 类的 Visibility 属性的数据绑定源吗?
  • SaveChangesUserControl 的可见性将绑定到使用用户控件的页面上的属性。主页面可以查看CanGo的值,但是主页面怎么知道usercontrol中的一个按钮被点击了,CanGo被设置了呢?
  • 如您所说,我已尝试从 UserControl 实例中获取返回值。但是,在 MainPage 的方法中,很难找到一种方法来知道用户控件的点击事件是否发生。我们可以实现的方式是在单击事件处理程序中执行您需要的导航操作。

标签: c# uwp uwp-xaml uwp-c#


【解决方案1】:

您可以使用AutoResetEvent 类进行线程同步。发出信号后,释放单个等待线程后自动重置。

请检查以下代码:

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
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多