【问题标题】:Text Content only via button文本内容仅通过按钮
【发布时间】:2019-04-04 20:41:47
【问题描述】:

我正在尝试获得以下信息:在我的页面内,我有一个文本框和按钮。当用户在键盘上按“Enter”时,它应该与单击按钮相同。

我的代码大致如下:

<Page x:Class="MyApp.Pages.Page1"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  .....
  DataContext="{Binding Page1VM, Source={StaticResource Locator}}">

<Page.InputBindings>
    <KeyBinding 
        Key="Enter" 
        Command="{Binding Btn_ConfirmCommand}" />
</Page.InputBindings>
<Grid>
    <Grid >
     <TextBox Text="{Binding SelectedID}" />
     <Button  Command="{Binding Btn_ConfirmCommand}"/>
    </Grid>
</Grid>

ViewModel 内部:

public Page1VM()
{
   Btn_ConfirmCommand = new RelayCommand(Btn_ConfirmMethod);
}
...
void Btn_ConfirmMethod()
{
  MessageBox.Show(SelectedID);
}
public string SelectedID
{
    get{return selectedID;}
    set
    {
        Set(() => SelectedID, ref selectedID, value);
        RaisePropertyChanged("SelectedID");
    }
 }

问题:当我在文本框中写入一些内容并单击按钮时,消息框会打印内容,但如果我按下回车键则会打印一个空字符串

【问题讨论】:

  • 作为替代方法,您将按钮设置为默认值(XAML 中的Default="True"),以便它使用 ENTER

标签: c# wpf mvvm keydown


【解决方案1】:

BindingUpdateSourceTrigger设置为PropertyChanged

<TextBox Text="{Binding SelectedID, UpdateSourceTrigger=PropertyChanged}" />

这应该会导致源属性在每次击键时更新。默认值为LostFocus

【讨论】:

    猜你喜欢
    • 2014-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-30
    • 2013-08-13
    • 2019-04-13
    相关资源
    最近更新 更多