【问题标题】:C# MVVM How to add Command to TextBlockC# MVVM 如何将命令添加到 TextBlock
【发布时间】:2018-08-16 14:19:34
【问题描述】:

我正在尝试向我的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 但找不到?还是我错了?

【问题讨论】:

    标签: c# wpf mvvm command textblock


    【解决方案1】:

    尝试为绑定指定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 属性的原因。

    【讨论】:

    • 还有办法获取我点击的单元格对象吗?
    • 有一个 CommandParameter 属性。但是,如果您有其他问题,请提出一个新问题。
    猜你喜欢
    • 2011-10-23
    • 1970-01-01
    • 2021-01-12
    • 1970-01-01
    • 2012-03-04
    • 1970-01-01
    • 2020-03-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多