C# MVVM How to add Command to TextBlock

2019-08-20 19:19发布

I'm trying to add a command to my TextBlock but haven't had any success yet. I tried following:

In XAML I've got a ItemsControl where I'm adding my 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>

As you see I tried to add the MouseBinding like you would do it usually but since I'm adding the Textblocks via my MainWindowViewModel it isn't working.

MainWindowViewModel Code:

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)
{
    //...
}

I'm pretty new to MVVM and trying to learn the framework. What am I missing out? I guess since the ItemsSource is set to CellCollection it is looking for the TestCommand in there but can't find it? Or am I wrong?

1条回答
何必那么认真
2楼-- · 2019-08-20 20:10

Try to specify a RelativeSource for the binding:

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

The DataContext of the TextBlock in the ItemTemplate is the corresponding Cell object and not the MainWindowViewModel and that's why you can't bind directly to the TestCommand property.

查看更多
登录 后发表回答