0

I'm using a DataGrid in my .NET 8 WPF app. The datagrid is set to a data context from a third-party library. I'd like to add a button column (as a DatagridTemplateColumn) to call a function in my own view model. I can't seem to figure out how to make this work.

I tried this:

<DataGridTemplateColumn>
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <Button Content="Map" DataContext="viewmodels:vmView1" Command="{Binding OpenMapCommand}" />
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

In my view model vmView1:

public ICommand OpenMapCommand { get; private set; }

public vmView1()
{
    OpenMapCommand = new RelayCommand<object>(OpenMap);
}

Is this even possible?

Thanks.

Don

3
  • You could use a RelativeSource on the binding to find the DataContext of the Window See here for more details. stackoverflow.com/questions/84278/… Commented Dec 14, 2024 at 10:17
  • Ryan, thanks for that. I'm looking to bind to an ICommand on the view model, so I tried this: <Button Content="Map" Command="{Binding Path=DataContext.OpenMapCommand, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type viewmodels:vmView1}}}"/> Autocomplete finds the OpenMapCommand, but when I run it, I get a binding error because the data context is null. So I'm still missing something. Commented Dec 14, 2024 at 21:16
  • Ah, solved it. I have to reference the view, not the view model. Duh. Commented Dec 14, 2024 at 22:39

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.