我正在尝试绑定到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#很新,我浪费了两天试图回复文本框中的回车键!
提前谢谢你,
此致
尼尔
答案 0 :(得分:0)
绑定将在当前绑定上下文中查找指定的绑定Path
。默认情况下,它将是当前DataContext
。您可以使用ElementName
,Source
或RelativeSource
更改绑定上下文。因此,在您的情况下,假设BarcodeTextEnterKeyCommand
是ImportPanel
控件的属性,您可以为控件指定一些名称,然后更改命令绑定
<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>