我正在构建一个 WPF 自定义控件(注意:不是用户控件)。控件的c#代码定义如下:
using System.Windows;
using System.Windows.Controls;
using MvvmFoundation.Wpf;
namespace TextBoxWithInputBinding
{
public class AutoComp : Control
{
static AutoComp()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(AutoComp), new FrameworkPropertyMetadata(typeof(AutoComp)));
}
public AutoComp()
{
DownCommand = new RelayCommand(() =>
{
System.Diagnostics.Debug.WriteLine("Down");
});
PressedCommand = new RelayCommand(() =>
{
System.Diagnostics.Debug.WriteLine("Pressed");
});
}
public RelayCommand DownCommand
{
get { return (RelayCommand)GetValue(DownCommandProperty); }
set { SetValue(DownCommandProperty, value); }
}
public static readonly DependencyProperty DownCommandProperty =
DependencyProperty.Register("DownCommand", typeof(RelayCommand), typeof(AutoComp), new PropertyMetadata(null));
public RelayCommand PressedCommand
{
get { return (RelayCommand)GetValue(PressedCommandProperty); }
set { SetValue(PressedCommandProperty, value); }
}
public static readonly DependencyProperty PressedCommandProperty =
DependencyProperty.Register("PressedCommand", typeof(RelayCommand), typeof(AutoComp), new PropertyMetadata(null));
}
}
我在Generic.xaml中为控件定义模板,如下所示:
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:TextBoxWithInputBinding">
<Style TargetType="{x:Type local:AutoComp}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:AutoComp}">
<Border Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}"
>
<StackPanel>
<TextBox>
<TextBox.InputBindings>
<KeyBinding Key="Down" Command="{TemplateBinding DownCommand}"/>
</TextBox.InputBindings>
</TextBox>
<Button Content="Press me" Command="{TemplateBinding PressedCommand}"/>
</StackPanel>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
当我按下“按下我”按钮时,会触发 PressedCommand(输出窗口中出现“按下”一词 - 但是,当我输入文本框并按下向下键时,没有任何反应。
我需要做什么才能使 DownCommand 火起来?
所以我找到了答案:我需要常规绑定而不是模板绑定:我替换了
<KeyBinding Key="Down" Command="{TemplateBinding DownCommand}"/>
和
<KeyBinding Key="Down"
Command="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=DownCommand}"/>
我仍然想知道为什么 Button 绑定适用于 TemplateBinding 而 TextBox KeyBinding 没有!!!
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句