C# MVVM 如何将命令添加到 TextBlock

C# MVVM How to add Command to TextBlock

我正在尝试向我的 TextBlock 添加命令,但尚未成功。我试过以下:

在 XAML 我有一个 ItemsControl 我要在其中添加我的 TextBlocks:

<ItemsControl ItemsSource="{Binding CellCollection}">
                <ItemsControl.ItemTemplate>
                    <DataTemplate>
                        <TextBlock Background="{Binding Path=CellBackgroundColor}">
                            <TextBlock.InputBindings>
                            <MouseBinding Command="{Binding TestCommand}" MouseAction="LeftClick"/>
                            </TextBlock.InputBindings>
                        </TextBlock>                       
                    </DataTemplate>
                </ItemsControl.ItemTemplate>
            <ItemsControl.ItemsPanel>
                <ItemsPanelTemplate>
                      <UniformGrid Grid.Row="0" Rows="25" Columns="25">
                </UniformGrid>
                </ItemsPanelTemplate>
            </ItemsControl.ItemsPanel>
            </ItemsControl>

如您所见,我尝试像往常一样添加 MouseBinding,但由于我是通过我的 MainWindowViewModel 添加 Textblocks,所以它不起作用。

MainWindowViewModel 代码:

public MainWindowViewModel()
{
    TestCommand = new RelayCommand(Test);
    CellCollection = new ObservableCollection<Cell>();

    for (int iRow = 1; iRow < 26; iRow++)
    {
        for (int iColumn = 1; iColumn < 26; iColumn++)
        {
            CellCollection.Add(new Cell() { Row = iRow, Column = iColumn, IsAlive = false, CellBackgroundColor = new SolidColorBrush(Colors.Red) });
        }
    }
}

void Test(object parameter)
{
    //...
}

我是 MVVM 的新手,正在尝试学习该框架。我错过了什么?我想由于 ItemsSource 设置为 CellCollection,所以它正在寻找 TestCommand 但找不到它?还是我错了?

尝试为绑定指定 RelativeSource

<TextBlock Background="{Binding Path=CellBackgroundColor}">
    <TextBlock.InputBindings>
        <MouseBinding Command="{Binding DataContext.TestCommand, 
                    RelativeSource={RelativeSource AncestorType=ItemsControl}}" MouseAction="LeftClick"/>
    </TextBlock.InputBindings>
</TextBlock>

ItemTemplateTextBlockDataContext 是相应的 Cell 对象而不是 MainWindowViewModel 这就是为什么你不能绑定直接到 TestCommand 属性.