Bubbling RoutedEvent or RoutedCommand in ViewModel

I have a collection of ViewModels that display as tabs, using a style to pull out the appropriate content to display on the tab:

public class TabViewModel : DependencyObject
{
      public object Content
      {
          get { return (object)GetValue(ContentProperty); }
          set
          {
              SetValue(ContentProperty, value);
          }
      }

}

Here's the TabControl:

<TabControl 
     ItemsSource={Binding MyCollectionOfTabViewModels}" 
     ItemContainerStyle="{StaticResource TabItemStyle}" />

And here is the style

<Style TargetType="TabItem" x:Key="TabItemStyle">
     <Setter Property="Content" Value="{Binding Content}"/>
</Style>

We instantiate the usercontrol and set the Content property for the TabViewModel so that the usercontrol appears in the TabItem content area.

MyCollectionOfViewModels.Add(new TabViewModel() 
{ 
     Content = new MyUserControl();
});

My question is: I would like to enable MyUserControl (or any of its subcontrollers) added to the TabViewModel content property in order to allow raising the event that TabViewModel is handling .

Does anyone know how I will do this?

RoutedEvents RoutedCommands, - 100% MVVM. , RoutedEvent RoutedCommand, , , .

. , Prism, , - , , Prism RegionManager.

+5
3

State TabViewModel DependencyPropertyChanged.

, :

public enum TabViewModelState
{
    True,
    False,
    FileNotFound
}

State TabViewModel :

public static readonly DependencyProperty StateProperty =
    DependencyProperty.Register("State", typeof(TabViewModelState), typeof(TabViewModel), new PropertyMetadata(OnStateChanged));

private static void OnStateChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
    TabViewModel viewModel= (TabViewModel)obj;

    //Do stuff with your viewModel
}

:

<CheckBox Checked="{Binding Path=State, Converter={StaticResource StateToBooleanConverter}, Mode=TwoWay}" />

, : , , , ( boolean ↔ TabViewModelState):

public class StateToBooleanConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        TabViewModelState state = (TabViewModelState) value;
        return state == TabViewModelState.True;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        bool result = (bool) value;
        return result ? TabViewModelState.True : TabViewModelState.False;
    }
}

, State, , , .

, !

+2

ViewModel UserControl, . , UserControl .

"GoCommand" ViewModel, UserControls :

<Button Command="{Binding GoCommand}" >Go</Button>

, , UserControl , - , ViewModel.

, , !;)

+1

You should take a look at the Marlon Grech Attached Command Behavior , which allows you to attach the ViewModel command to a GUI event.

+1
source

All Articles