首页 > 解决方案 > 如何在 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;
}

标签: c#wpfmvvmbindingcommandparameter

解决方案


将 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;
}

推荐阅读