【发布时间】: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