WPF - einfaches Commandbindung
Kleines Snippet wie man unter C-Sharp ein einfaches Commandbinding realisiert.
Die Logik (TestWindow.xaml.cs"):
public partial class TestWindow : Window
{
public TestWindow()
{
InitializeComponent();
CommandBinding cb = new CommandBinding(TestCommand,
TestCommand_Executed,
TestCommand_CanExecute);
this.CommandBindings.Add(cb);
}
public static readonly RoutedUICommand TestCommand =
new RoutedUICommand("TestCommand",
"testencom",
typeof(TestWindow));
private void TestCommand_CanExecute(object sender,
CanExecuteRoutedEventArgs e)
{
if (txtBox.Text.Length > 0 && txtBox.Text.Length < 10)
{
e.CanExecute = true;
}
else
{
e.CanExecute = false;
}
}
private void TestCommand_Executed(object sender,
ExecutedRoutedEventArgs e)
{
MessageBox.Show("executed!!!");
}
}
Die Ansicht (TestWindow.xaml)
<Window x:Class="WpfSpielwiese.GUI.Main.TestWindow"
xmlns:commands="clr-namespace:WpfSpielwiese.GUI.Main"
...>
<StackPanel>
...
<Button Name="btn" Content="btn" Command="commands:TestWindow.TestCommand" />
</StackPanel>
</Window>