C#MVVM如何将命令添加到TextBlock [英] C# MVVM How to add Command to TextBlock
问题描述
我正在尝试向我的 TextBlock
添加命令,但还没有成功。我尝试了以下操作:
I'm trying to add a command to my TextBlock
but haven't had any success yet. I tried following:
在XAML中,我有一个 ItemsControl
,在其中添加了我的 TextBlocks
:
In XAML I've got a ItemsControl
where I'm adding my 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
的,因此它不起作用。
As you see I tried to add the MouseBinding
like you would do it usually but since I'm adding the Textblocks
via my MainWindowViewModel
it isn't working.
MainWindowViewModel代码:
MainWindowViewModel Code:
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
,但找不到它?还是我错了?
I'm pretty new to MVVM and trying to learn the framework. What am I missing out? I guess since the ItemsSource
is set to CellCollection it is looking for the TestCommand
in there but can't find it? Or am I wrong?
推荐答案
尝试为绑定指定 RelativeSource
:
<TextBlock Background="{Binding Path=CellBackgroundColor}">
<TextBlock.InputBindings>
<MouseBinding Command="{Binding DataContext.TestCommand,
RelativeSource={RelativeSource AncestorType=ItemsControl}}" MouseAction="LeftClick"/>
</TextBlock.InputBindings>
</TextBlock>
<$ c $的 DataContext
ItemTemplate
中的c> TextBlock 是对应的 Cell
对象,而不是 MainWindowViewModel
,这就是为什么您不能直接绑定到 TestCommand
属性的原因。
The DataContext
of the TextBlock
in the ItemTemplate
is the corresponding Cell
object and not the MainWindowViewModel
and that's why you can't bind directly to the TestCommand
property.
这篇关于C#MVVM如何将命令添加到TextBlock的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!