[英]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
。 您可以使用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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.