0
私はカスタムグリッド(オブジェクト)がビューモデル内の何かを "実行"したいと思っています。 - これを分割する正しい方法をGoogleから検索するには、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>
'CustomGrid'は正しく表示されていますか? 私は、DependencyPropertiesと "独自のコントロールを設計する方法"に精通することをお勧めします。 'DataContext'を設定する方法は最良の方法ではありません。 –
はい、ここに表示するコードをコンパクトにするには、この方法で行いました。 – paul23
*「プログラムでこれをやりたがっています」* - それは本当に必要条件ですか?彼らはあなたが必要とするよりもはるかに難しいものになっています。 –