Davita
Davita

Reputation: 9114

WPF. Disable/Enable ListBox items ContextMenu & MVVM

I have a listbox with several items. This items could be in 3 state:

I need to assign a context menu on each of those items. Actually, I want to have one list of menu items to reuse for each listbox items and I want to disable/enable menu items according to their state. I'm using MVVM. I wanted to know what's best practice to achieve my goal?

    <DataTemplate x:Key="TemplateSelector">
        <ContentPresenter Content="{Binding}" Name="contentPresenter">
            <telerik:RadContextMenu.ContextMenu>
                <telerik:RadContextMenu>
                    <telerik:RadMenuItem Header="Connect" Style="{StaticResource ResourceKey=ContextMenuStyle}" />
                    <telerik:RadMenuItem Header="Disconnect" />
                    <telerik:RadMenuItem Header="Delete Database" />
                </telerik:RadContextMenu>
            </telerik:RadContextMenu.ContextMenu>
        </ContentPresenter>

        <DataTemplate.Triggers>
            <DataTrigger Binding="{Binding Path=ConnectionType}" Value="Disconnected">
                <Setter TargetName="contentPresenter" Property="ContentTemplate" Value="{StaticResource OfflineDeviceItemTemlpate}" />
            </DataTrigger>
            <DataTrigger Binding="{Binding Path=ConnectionType}" Value="Internet">
                <Setter TargetName="contentPresenter" Property="ContentTemplate" Value="{StaticResource OnlineDeviceItemTemplate}" />
            </DataTrigger>
            <DataTrigger Binding="{Binding Path=ConnectionType}" Value="Wifi">
                <Setter TargetName="contentPresenter" Property="ContentTemplate" Value="{StaticResource OnlineDeviceItemTemplate}" />
            </DataTrigger>
        </DataTemplate.Triggers>
    </DataTemplate>
</UserControl.Resources>


<Grid>
    <telerik:RadListBox x:Name="lsbDevices" ItemsSource="{Binding Path=Devices}" ItemTemplate="{StaticResource TemplateSelector}" 
                        SelectedItem="{Binding SelectedDevice, Mode=TwoWay}" Grid.Row="0" />
</Grid>

I'm thinking adding a property for each menu item in ModelView which will state if the corresponding menu item should be enabled or not (For example, public bool ConnectEnabled {...}). Is this a good approach or I'm doing something very wrong here?

Thanks

Upvotes: 0

Views: 1549

Answers (1)

pchajer
pchajer

Reputation: 1584

I think this is a UI logic and you should not write it in XAML.. I would suugest you can have a class which gets binded to list box items and this class will have a state object or property which will maintain the enable/disable logic for context menu. You can bind this proeprty to context menu.

Upvotes: 1

Related Questions