c# - 如何在 UI 中单击对象从 ObservableCollection 中获取对象?
问题描述
我有一个 TextBlocks 字段,当我单击一个命令触发器时,它会在统一网格中显示。我现在如何获取从显示的集合中单击的特定对象?
有关更多信息,请查看我之前关于文本块上的命令的问题: C# MVVM How to add Command to TextBlock
XAML:
<ItemsControl ItemsSource="{Binding CellCollection}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBlock Background="{Binding Path=CellBackgroundColor}">
<TextBlock.InputBindings>
<MouseBinding Command="{Binding DataContext.TestCommand, RelativeSource={RelativeSource AncestorType=ItemsControl}}" MouseAction="LeftClick"/>
</TextBlock.InputBindings>
</TextBlock>
</DataTemplate>
</ItemsControl.ItemTemplate>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<UniformGrid Grid.Row="0" Rows="25" Columns="25">
</UniformGrid>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
视图模型:
public ObservableCollection<Cell> CellCollection { get; set; }
public MainWindowViewModel()
{
StartCommand = new RelayCommand(Start);
StopCommand = new RelayCommand(Stop);
TestCommand = new RelayCommand(Test);
CellCollection = new ObservableCollection<Cell>();
//begins with 1 not 0
//generates 625 cells for the field (25x25)
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.Transparent) });
}
}
}
我尝试了以下事情,但没有成功:
<MouseBinding CommandParameter="{Binding CTest}" Command="{Binding DataContext.TestCommand, RelativeSource={RelativeSource AncestorType=ItemsControl}}" MouseAction="LeftClick"/>
财产
Cell _CTest;
public Cell CTest
{
get
{
return _CTest;
}
set
{
if(_CTest != value)
{
_CTest = value;
RaisePropertyChanged("CTest");
}
}
}
void Test(object parameter)
{
Cell test = CTest;
}
解决方案
将 MouseBinding 中的 CommandParameter 直接绑定到 DataTemplate 项:
<MouseBinding
Command="{Binding DataContext.TestCommand, RelativeSource={RelativeSource AncestorType=ItemsControl}}"
CommandParameter="{Binding}"
MouseAction="LeftClick"/>
command 方法将通过参数接收它:
void Test(object parameter)
{
Cell test = (Cell)parameter;
}
推荐阅读
- python - 比较多组列表(Python)
- redwoodjs - 如何在 RedwoodJS 上创建字段解析器
- javascript - 悬停时滚动链接文本 - 无尽的选框效果
- flutter - 从 main() 调用 await rootBundle.loadString(...) 时,Flutter 应用程序挂起
- azure-cosmosdb - IdentityServer Access Token 长度短
- html - 除非在角色后面,否则 HR 不会出现
- go - 尝试连接到 localhost 时出现“连接:连接被拒绝”
- mysql - 使用 nodejs 后端、角度前端和 mysql db 上传和显示图像
- java - 使用 Chaquopy 在 Android 上将字节数组从 java 传递到 python
- ruby-on-rails - 是什么导致我的 Rails 模型失败?