【问题标题】:Programmatically Click PrimaryButton of ContentDialog以编程方式单击 ContentDialog 的 PrimaryButton
【发布时间】:2018-05-07 22:35:59
【问题描述】:

在 UWP 中,当文本框的 KeyDown 事件检测到已按下 Enter 时,如何以编程方式单击 ContentDialog 的 PrimaryButton?只是尝试添加一个键盘快捷方式以在文本框中接受答案并从键盘全部关闭对话框,而无需移动鼠标并单击确定。

private void A1TextBox_KeyDown(object sender, KeyRoutedEventArgs e)
{
    if (e.Key == Windows.System.VirtualKey.Enter)
    {
        // Programmatically Click PrimaryButton Here        
    }
}

<ContentDialog
    x:Class="App1.ContentDialog1"
    Title="DialogBox"
    Loaded="ContentDialog_Loaded"
    PrimaryButtonText="Ok"
    SecondaryButtonText="Cancel"
    PrimaryButtonClick="ContentDialog_PrimaryButtonClick"
    SecondaryButtonClick="ContentDialog_SecondaryButtonClick">

<Grid Name="A1Grid">
    <Grid.RowDefinitions>
        <RowDefinition Height="auto"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>
    <TextBox Name="A1TextBox" Grid.Row="0" 
        PlaceholderText="Search String" 
        TextChanged="A1TextBox_TextChanged" 
        KeyDown="A1TextBox_KeyDown"/>
    <ScrollViewer Grid.Row="1" 
         ScrollViewer.VerticalScrollBarVisibility="Auto"
         VerticalAlignment="Stretch">
        <ListBox Name="A1ListBox" MinHeight="200"/>
    </ScrollViewer>
</Grid>
</ContentDialog>

【问题讨论】:

标签: c# uwp


【解决方案1】:

使用以下代码:

RoutedEventArgs f;

private void A1TextBox_KeyDown(object sender, KeyRoutedEventArgs e)
{
    if (e.Key == Windows.System.VirtualKey.Enter)
    {
        ContentDialog_PrimaryButtonClick (Sender, f);       
    }
}

然后他会触发 PrimaryButtonClick 事件。

【讨论】:

    【解决方案2】:

    你有没有试过把你想点击的按钮变成“AcceptButton”?

    //This goes in the form loading method
    this.AcceptButton = PrimaryButton;
    

    这应该把按钮变成蓝色,当在表单上按下回车键时会调用 click 函数。项目

    编辑:刚刚注意到这不适用于 winforms。

    this.DefaultButton = PrimaryButton;
    

    谢谢比尔!

    【讨论】:

    • 这个问题是针对 UWP 而不是 WinForms。 UWP 没有 ContentDialog 的 AcceptButton 属性。
    • 他们在 UWP 中将 WinForm AcceptButton 重命名为 DefaultButton。
    • 啊,抱歉,错过了。还在习惯过滤器。
    【解决方案3】:

    UWP ContentDialog 文档指出:

    “您可以选择区分三个按钮之一作为对话框的默认按钮。使用 DefaultButton 属性来区分其中一个按钮。此按钮将接收Accent Button 视觉处理,自动响应 ENTER 键,并在对话框打开时获得焦点,除非对话框的内容包含可聚焦元素。"

    如下更改ContentDialog:

    <ContentDialog … DefaultButton="Primary">
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-30
      • 1970-01-01
      • 2013-10-09
      • 2011-10-22
      • 2015-03-17
      • 1970-01-01
      • 1970-01-01
      • 2014-01-08
      相关资源
      最近更新 更多