繁体   English   中英

在C#中使用XAML和WPF绑定文本框

[英]Keybinding a TextBox using XAML and WPF in C#

我试图绑定到WPF UserControl中的键事件。 该组件是一个TextBox,而我的XAML是

<TextBox Name="textBarCode" Grid.Row="1" Grid.Column="1" Grid.ColumnSpan="2" HorizontalAlignment="Left" VerticalAlignment="Center" Margin="0,0,10,0"  Width="300">
    <TextBox.InputBindings>
        <KeyBinding Key="Enter" Command="{Binding ImportPanel.BarcodeTextEnterKeyCommand}"/>
        <KeyBinding Key="Tab" Command="{Binding ImportPanel.BarcodeTextTabKeyCommand}"/>
    </TextBox.InputBindings>
</TextBox>

我不确定是否需要它,但名称空间声明是

<UserControl x:Class="Scimatic.Samples.Actions.ImportPanel"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:ig="http://schemas.infragistics.com/xaml" 
    xmlns:components="clr-namespace:Scimatic.Mondrian.Components;assembly=Mondrian"
    xmlns:sampleInventory="clr-namespace:Scimatic.Mondrian.Views.SampleInventory;assembly=Mondrian"
    xmlns:trackingTags="clr-namespace:Scimatic.Mondrian.Views.TrackingTags;assembly=Mondrian">

在基本xaml.cs文件中声明命令的代码是

_barcodeKeyCommand = new ActionCommand(() =>
{
    if (!_parent && FocusableTagOnBarcode != null)
    {
        trackingInfo.SetFocusOnTag(FocusableTagOnBarcode);
    }
    else
    {
    buttonImport.Focus();
    }
});

设置这些属性的代码是:

/// <summary>
/// The command property for the enter key in the barcode text box
/// </summary>
public ICommand BarcodeTextTabKeyCommand
{
    get
    {
        return _barcodeKeyCommand;
    }
}

The commands are returned in the same class using the same method:

/// <summary>
/// The command property for the enter key in the barcode text box
/// </summary>
public ICommand BarcodeTextEnterKeyCommand
{
    get
    {
        return _barcodeKeyCommand;
    }
}

但是,不管我尝试什么(并且我已经尝试过各种方法); 我只是无法获取要调用的命令。 我显然已经做了一些事情,但是有人可以帮我吗。 我对C#相当陌生,浪费了两天时间试图在文本框中响应回车键!

先感谢您,

问候,

尼尔

绑定将在当前绑定上下文中查找指定的绑定Path 默认情况下,它将是当前的DataContext 您可以使用ElementNameSourceRelativeSource更改绑定上下文。 因此,在您的情况下,假设BarcodeTextEnterKeyCommandImportPanel控件的属性,则可以为控件命名,然后更改命令绑定

<UserControl 
    x:Class="Scimatic.Samples.Actions.ImportPanel"
    ...
    x:Name="myUserControl">
    <!-- ... -->
    <TextBox Name="textBarCode" ....>
        <TextBox.InputBindings>
            <KeyBinding Key="Enter" Command="{Binding ElementName=myUserControl, Path=BarcodeTextEnterKeyCommand}"/>
            <KeyBinding Key="Tab" Command="{Binding ElementName=myUserControl, Path=BarcodeTextEnterKeyCommand}"/>
        </TextBox.InputBindings>
    </TextBox>
    <!-- ... -->
</UserControl>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM