WPF Binding : Add Button to Unbound Field in grid

2019-07-24 04:01发布

问题:

I am trying to add a button to an unbound field in XamDataPresenter.

Here is the button template:

        <Style x:Key="CancelButtonTemplate" TargetType="{x:Type igDP:CellValuePresenter}">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type igDP:CellValuePresenter}">
                        <Button x:Name="CancelButton" Content="Cancel" Command="{Binding CancelButtonCommand}" Width="80" Height="20" />
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>

And here is the unbound field in XamDataPresenter:

                    <igDP:UnboundField Name="CancelOrder" Label="Cancel Order" Column="11">
                        <igDP:UnboundField.Settings>
                            <igDP:FieldSettings CellValuePresenterStyle="{StaticResource CancelButtonTemplate}" CellHeight="12" CellWidth="50">
                            </igDP:FieldSettings>
                        </igDP:UnboundField.Settings>
                    </igDP:UnboundField>                       
                </igDP:FieldLayout.Fields>   

The "CancelButtonCommand" that the button is bound to is a public property in the viewmodel and i have verified that it works with a button outside the XamDataPresenter and without a template.

The button shows up in the grid but nothing happens when i press it.

What am i doing wrong?

回答1:

I believe you need to add a little to your binding in the style. Try changing to this:

<Button Command="{Binding DataContext.CancelButtonCommand, RelativeSource={RelativeSource AncestorType={x:Type igDP:XamDataGrid}}}"
                                CommandParameter="{Binding}">

Are you using XamDataPresenter or XamDataGrid? if presenter, change the above x:Type to XamDataPresenter instead of XamDataGrid

Also:If i remember, I had to add the CommandParameter so the command would know which row to act upon, and i needed SelectedItem inside that method. Otherwise, every button would act exactly the same. In my case, each button is supposed to do something to the object of the row it was in.



回答2:

Use button as below(element binding):

 <Button x:Name="CancelButton" Content="Cancel" Command="{Binding  ElementName=theotherbuttonworkingthiscommand,Path=DataContext.CancelButtonCommand}" Width="80" Height="20" />

or use relative Source binding:

<Button Command="{Binding RelativeSource={RelativeSource AncestorType={x:Type window}},Path=DataContext.CancelButtonCommand}">