2014-03-29 88 views
0

我在使用WPF進行控制綁定時發現一些簡單的示例時遇到了一些困難,我希望能夠通過這個簡單的示例幫助我解決問題。簡單的C#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"); 
     } 
    } 
} 

當我運行它,我得到的錯誤

「成員 「CommandEnterKeyPressed」 無法識別或不 可訪問「和」無過載「'ommandEnterKeyPressed'匹配 委託'System.Windows.Input.Executed RoutedEventHandler'」。

有什麼簡單的我失蹤了嗎?

謝謝。

回答

1

變化CanExecuteRoutedEventArgsExecutedRoutedEventArgs

private void CommandEnterKeyPressedExecuted(object sender, CanExecuteRoutedEventArgs e) 

應該

private void CommandEnterKeyPressedExecuted(object sender, ExecutedRoutedEventArgs e) 

CanExecuteRoutedEventArgs用於CanExecute事件。你也應該刪除此行

private static RoutedUICommand CommandEnterKeyPressed; 

,並留下您RoutedUICommand

+0

的唯一公開聲明哇 - 簡直不敢相信我沒有斑的!謝謝!這有助於我走上正軌。 我現在遇到了XML中標記的問題「Value can not be null。Parameter name:value」 - 你知道可能會導致什麼嗎? – Ekins86

+0

因此'CommandBinding'現在有'Command'和'Executed'事件處理程序?設計中的問題是? – dkozl

+0

謝謝 - 是的,我在創建RoutedUICommand之前初始化了組件。現在完美工作,謝謝你的幫助:D – Ekins86