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

标签 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在里面但是找不到?还是我错了?

最佳答案

尝试指定 RelativeSource对于绑定(bind):

<TextBlock Background="{Binding Path=CellBackgroundColor}">
    <TextBlock.InputBindings>
        <MouseBinding Command="{Binding DataContext.TestCommand, 
                    RelativeSource={RelativeSource AncestorType=ItemsControl}}" MouseAction="LeftClick"/>
    </TextBlock.InputBindings>
</TextBlock>
DataContextTextBlockItemTemplate是对应的Cell对象而不是 MainWindowViewModel这就是为什么你不能直接绑定(bind)到 TestCommand属性(property)。

关于C# MVVM 如何将命令添加到 TextBlock,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51879288/

相关文章:

c# - 使用 Unity/Prism/MVVM 的 ObjectContext 构造函数注入(inject)

c# - WPF 用户控件库中的 UserControl 绑定(bind)不适用于 ContentControl

c# - PlotView 和 Plot 之间有什么不同?

C# - SQLite SELECT 查询 * 返回数据类型

c# - 如何在非 UI 线程中使用 reg-free COM?

wpf - 在 WPF 中,如何获取 tabItem 的内容以填充可用空间?

c# - View 中的控件如何从 View 模型中获取特定数据?

c# - linq-to-sql .All() 或 .Any() 查找匹配条件的所有项目

c# - POST 期间的双重等待操作

c# - 使用 csvHelper 序列化子类