user366113
user366113

Reputation: 11

WPF ContextMenu bind some property to another property of the same control

I have a ContextMenu and a ColumnHeaderStyle defined in Window.Resource section which I use-it to a DataGrid ColumnHeader. My code is something like this:

<ContextMenu x:Key="cm_columnHeaderMenu"/>

<Style x:Key="DefaultColumnHeaderStyle" TargetType="{x:Type DataGridColumnHeader}">
    <Setter Property="ContextMenu" Value="{StaticResource cm_columnHeaderMenu}" />
</Style>

<DataGrid Grid.Column="2" Grid.Row="1" x:Name="dgridFiles" IsReadOnly="True" 
 ColumnHeaderStyle="{StaticResource DefaultColumnHeaderStyle}">

I want to know if I can (and if the answer it true, then HOW I can I do it) bind the ContextMenu Visibility property to same control ContextMenu Items.Count > 0 property.

Initially based on some other treeView control selections made there shoud be no items in the context menu, but i wish to add dinamically items in ContextMenu based on selection in treeView. This part is done, the context has those items. On some selections there are no-items, but still on the grid it appears an empty ContextMenu. So I believe the easiest part it would be to bind the Visibility to Items.Count property of the same control.

Sorry if my english is not good enough, I'll try to explain better if i didnt make clear 1st time.

Upvotes: 1

Views: 1398

Answers (3)

Lunivore
Lunivore

Reputation: 17677

Try a converter to convert the value of the item count to a boolean. So you'll end up with something like

<ContextMenu Visibility={Binding RelativeSource={RelativeSource Self},
 Converter={StaticResource ItemsToVisibilityConverter}, Path=Items.Count}} />

If that doesn't work, try this with data triggers (you still need a converter anyway, and this shows a converter at work):

http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/a8ad8c14-95aa-4ed4-b806-d0ae874a8d26/

Upvotes: 0

Amsakanna
Amsakanna

Reputation: 12954

Using this you can bind to the property in the same control

Visibility="{Binding Path=Items.Count, RelativeSource={RelativeSource Self}}"

You also have to use a converter to achieve what you want.

Just in case you need this

Upvotes: 1

DHN
DHN

Reputation: 4865

you want to bind via RelativeSource, especially the Self mode.
I think by reading this or this you will be able to achieve your goal.

Then you'll need a binding converter to convert the integer values to the matching type and values of the Visibility property. You'll find a short tutorial here.

Regards

Upvotes: 2

Related Questions