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

时间:2018-08-16 14:19:35

标签: c# wpf mvvm command 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,但是由于我是通过Textblocks添加MainWindowViewModel的,因此无法正常工作。

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,但找不到它?还是我错了?

1 个答案:

答案 0 :(得分:2)

尝试为绑定指定RelativeSource

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

{{1}中DataContext中的TextBlock是对应的ItemTemplate对象,而不是Cell,这就是为什么您不能直接绑定到MainWindowViewModel属性。