In this example the IsEnabled property of my button is bound to the selected rows "Local" property of the grid and it works just fine:
<Button DockPanel.Dock="Bottom" Width="100" Height="100" IsEnabled="{Binding ElementName=dataGridRestore , Path=SelectedItem.Local}"></Button>
<my:DataGrid x:Name="dataGridRestore"
ItemsSource="{Binding}"
>
<my:DataGrid.ContextMenu>
<ContextMenu Name="restoreCntextMenu">
<MenuItem Header="Open" />
</ContextMenu>
</my:DataGrid.ContextMenu>
<my:DataGridCheckBoxColumn Header="Local" Binding="{Binding Local}" />
</my:DataGrid>
Now when I move the button from outside my grid to inside the context menu of the grid my binding doesn't work. Why is this and how can i fix it?
<my:DataGrid x:Name="dataGridRestore"
ItemsSource="{Binding}"
>
<my:DataGrid.ContextMenu>
<ContextMenu Name="restoreCntextMenu">
<MenuItem Header="Open"开发者_如何学Python />
<Button Width="100" Height="100" IsEnabled="{Binding ElementName=dataGridRestore , Path=SelectedItem.Local}"></Button>
</ContextMenu>
</my:DataGrid.ContextMenu>
<my:DataGridCheckBoxColumn Header="Local" Binding="{Binding Local}" />
</my:DataGrid>
Use this code:
<ContextMenu DataContext="{Binding PlacementTarget.SelectedItem, RelativeSource={RelativeSource Self}}">
<Button IsEnabled="{Binding Local}"/>
</ContextMenu>
I tested it with ContextMenu of DataGridRows and it worked fine.
What about using the RelativeSource attribute instead of the ElementName?
can't test it right now but something like this :
<Button Width="100" Height="100" IsEnabled="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type my:DataGrid}},Path=SelectedItem.Local}"></Button>
精彩评论