我正在尝试将命令添加到我的 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>
DataContext
的TextBlock
在 ItemTemplate
是对应的Cell
对象而不是 MainWindowViewModel
这就是为什么你不能直接绑定(bind)到 TestCommand
属性(property)。
关于C# MVVM 如何将命令添加到 TextBlock,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51879288/