繁体   English   中英

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>

ItemTemplate TextBlockDataContext是对应的Cell对象,而不是MainWindowViewModel ,这就是为什么您不能直接绑定到TestCommand属性。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM