我希望我的自定义网格(对象)能够在viewmodel中“执行”某些内容。 - 通过谷歌搜索分割它的正确方法是使用带有Grid.InputBindings
字段的命令。
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
namespace testit
{
public class ViewModel
{
public static readonly RoutedCommand ClickCommand =
new RoutedUICommand("ClickCommand", "ClickCommand", typeof(ViewModel));
void SelectElementCanExecute(object sender, CanExecuteRoutedEventArgs e) {
// The Window gets to determine if the Foo
// command can execute at this time.
e.CanExecute = true;
}
void SelectElementExecute(object sender, ExecutedRoutedEventArgs e) {
// The Window executes the command logic when the user wants to Foo.
MessageBox.Show("The Window is Fooing...");
}
}
public class CustomGrid : Grid
{
private TextBlock tb;
public CustomGrid(ViewModel model) {
tb = new TextBlock();
tb.Text = "hello world";
Children.Add(tb); // just to show something
Background = new SolidColorBrush(Colors.LightGray);
DataContext = model;
var binding = new MouseBinding(ViewModel.ClickCommand,
new MouseGesture(MouseAction.LeftClick));
InputBindings.Add(
binding
);
}
}
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private ViewModel vm;
public MainWindow() {
InitializeComponent();
var t = Content as Grid;
vm = new ViewModel();
t.Children.Add(new CustomGrid(vm));
}
}
}
我希望网格视图显示网格 - 当我点击它时会显示一个消息框。 - 或者至少调试器应该停在我放在那里的断点上。
但似乎没有发生任何事情:好像网格没有正确调用ClickCommand。 - 显然我没有正确注册一切。这样做的正确方法是什么?
为了完整性,这里是xaml(虽然我不希望在xaml文件中设置绑定,但我希望以编程方式执行此操作):
<Window x:Class="testit.MainWindow"
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"
xmlns:local="clr-namespace:testit"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid>
</Grid>
</Window>
答案 0 :(得分:1)
您错过了CommandBinding
:
public class CustomGrid : Grid
{
private TextBlock tb;
public CustomGrid(ViewModel model)
{
tb = new TextBlock();
tb.Text = "hello world";
Children.Add(tb); // just to show something
Background = new SolidColorBrush(Colors.LightGray);
DataContext = model;
var binding = new MouseBinding(ViewModel.ClickCommand, new MouseGesture(MouseAction.LeftClick));
InputBindings.Add(binding);
var commandBinding = new CommandBinding(ViewModel.ClickCommand, SelectElementExecute);
CommandBindings.Add(commandBinding);
}
void SelectElementExecute(object sender, ExecutedRoutedEventArgs e)
{
// The Window executes the command logic when the user wants to Foo.
MessageBox.Show("The Window is Fooing...");
}
}