-1

I have a data grid that lists information present in an observable collection. So far everything is working fine.

I would then like to add a stop command which Name property as a parameter but when i write CommandParameter= {Binding Name}, my button is disable. I try to set CommandParameter with a random string and that's working, so the probleme comes from the binding.

        <DataGrid.Columns>


            <DataGridTextColumn Header="Name" Binding="{ Binding Name }"/>
            <DataGridTextColumn Header="Source" Binding="{ Binding Source }"/>
            <DataGridTextColumn Header="Target" Binding="{ Binding Target }"/>

            <DataGridTemplateColumn Header="Stop">
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <Button Content="Stop" 
                                Command="{ Binding DataContext.StopCommand, RelativeSource = { RelativeSource FindAncestor,AncestorType={ x:Type DataGrid } } }"                         
                                CommandParameter="{ Binding Name }"/>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>

Thanks you !

4

1 回答 1

1

我认为这个问题出在您的代码隐藏代码中。我为您创建了一个示例,在此示例中,我使用的是您的 XAML 代码。

在此示例中,我使用的是Prism.WPF NuGet 包。

XAML 代码:

<DataGrid ItemsSource="{Binding Items}" AutoGenerateColumns="False">
    <DataGrid.Columns>
        <DataGridTextColumn Header="Name" Binding="{Binding Name}"/>
        <DataGridTextColumn Header="Source" Binding="{Binding Source}"/>
        <DataGridTextColumn Header="Target" Binding="{Binding Target}"/>
        <DataGridTemplateColumn Header="Stop">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <Button Content="Stop" 
                            Command="{Binding DataContext.StopCommand, RelativeSource={RelativeSource FindAncestor,AncestorType={x:Type DataGrid}}}"                         
                            CommandParameter="{Binding Name}"/>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
        </DataGrid.Columns>
</DataGrid>

代码隐藏:

public partial class MainWindow : MetroWindow
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = new FooViewModel();
    }
}

public class Foo
{
    public string Name { get; set; }
}

public class FooViewModel : BindableBase
{
    public FooViewModel()
    {
        for (int i = 0; i < 100; i++) Items.Add(new Foo() { Name = $"name_{i}" });
        StopCommand = new DelegateCommand<string>(OnStopCommand);
    }

    public ICommand StopCommand { get; private set; }
    public ObservableCollection<Foo> Items { get; set; } = new ObservableCollection<Foo>();

    private void OnStopCommand(string name) => Console.WriteLine(name);
}
于 2020-04-19T16:08:08.740 回答