麻烦简单的C#WPF自定义控件

时间:2014-03-29 23:15:24

标签: c# wpf-controls

我在使用WPF时遇到控制绑定时遇到一些困难,我希望你可以通过这个简单的例子来帮助我理解它。

您能解释一下为什么这不起作用,也是一种让它运行的简单方法吗?

我看了很多教程,但在这个阶段它们对我来说仍然有点先进,我认为所以非常感谢任何帮助。

谢谢!

XAML:

<Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d" x:Class="DemoProject.MainWindow"
    xmlns:custom="clr-namespace:DemoProject"
    Title="DemoProject" >

    <TextBox x:Name="MyTextBox">
        <TextBox.InputBindings>
            <KeyBinding Key="Enter" Command="{x:Static custom:MainWindow.CommandEnterKeyPressed}" 
                CommandParameter="{Binding Path=Text, RelativeSource={RelativeSource AncestorType={x:Type TextBox}}}" />
        </TextBox.InputBindings>
    </TextBox>

    <Window.CommandBindings>
        <CommandBinding Command="{x:Static custom:MainWindow.CommandEnterKeyPressed}"
            Executed="CommandEnterKeyPressedExecuted" />
    </Window.CommandBindings>   
</Window>

C#:

namespace DemoProject
{
    public partial class MainWindow : Window
    { 
        private static RoutedUICommand CommandEnterKeyPressed;

        public MainWindow()
        {
            InitializeComponent();
        }

        public static RoutedUICommand CommandEnterKeyPressed = new RoutedUICommand();

        private void CommandEnterKeyPressedExecuted(object sender, CanExecuteRoutedEventArgs e)
        {
            MessageBox.Show("Enter key was pressed");
        }
    }
}

当我运行时,我收到错误

  

&#34;会员&#34; CommandEnterKeyPressed&#34;不被承认或不被认可   访问&#34;并且&#34;&#34;&#39; ommandEnterKeyPressed&#39;火柴   委托&#39; System.Windows.Input.ExecutedRoutedEventHandler&#39;&#34;。

我有什么简单的遗失吗?

感谢。

1 个答案:

答案 0 :(得分:1)

CanExecuteRoutedEventArgs更改为ExecutedRoutedEventArgs

private void CommandEnterKeyPressedExecuted(object sender, CanExecuteRoutedEventArgs e)

应该是

private void CommandEnterKeyPressedExecuted(object sender, ExecutedRoutedEventArgs e)

CanExecuteRoutedEventArgs用于CanExecute事件。您还应该删除此行

private static RoutedUICommand CommandEnterKeyPressed;

并仅保留RoutedUICommand

的公开声明