Search code examples
wpfms-accessuser-controlsviewmodelsiblings

Access ViewModel of sibling control


I am aware there are some similar threads but I am still not sure of the best implementation.

The code should be self explanatory - check the comment there. How best to access that VIewModel.

part:FontSearchBox is a UserControl without a ViewModel - It just holds a TextBox for searching which needs to execute the command.

Thanks and appreciated.

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="35" />
        <RowDefinition Height="90" />
        <RowDefinition Height="*" />
    </Grid.RowDefinitions>

    <part:MainWindowControls Grid.Row="0" VerticalAlignment="Stretch" HorizontalAlignment="Stretch" />

    <Grid Grid.Row="1">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="200" />
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>
        <Image Source="/Typesee;component/Resources/window_logo.png" Width="156" Height="45" Grid.Column="0" VerticalAlignment="Top" RenderOptions.BitmapScalingMode="NearestNeighbor" />

        <!-- THIS TEXTBOX NEEDS TO CALL A COMMAND (SearchCommand.Execute(string)) Which resides in the fontTreeViewControl's ViewModel (FontTreeViewModel) -->
        <part:FontSearchBox Grid.Column="1" HorizontalAlignment="Right" VerticalAlignment="Bottom" Margin="0,0,12,10" Width="250" DataContext="{Binding ElementName=fontTreeViewControl, Path=DataContext}" />
    </Grid>

    <vw:FontTreeView x:Name="fontTreeViewControl" Grid.Row="2" VerticalAlignment="Stretch" HorizontalAlignment="Stretch" />

</Grid>

Solution

  • if you sre using MVVMLight the You can use Event to Command for the ....

    in your UserControl <vw:FontTreeView /> you must be having a TextBox so in TextBox Xaml you have to Write

    Xaml

    <i:Interaction.Triggers>
        <i:EventTrigger EventName="TextChanged">
            <Commands:EventToCommand Command="{Binding Path=TextChangedCommand}"/>
        </i:EventTrigger>
    </i:Interaction.Triggers>
    

    To know more about the the Aliases see this link. it also demonstrates how to pass the event argument to your ViewModel.... but you might not meed that so you can skip it...

    If TextBox is outsite fontTreeViewControl.... then,

    <StackPanel DataContext={Binding Path=DataContext,ElementName=fontTreeViewControl}>
        <TextBox >
        <i:Interaction.Triggers>
        <i:EventTrigger EventName="TextChanged">
            <Commands:EventToCommand Command="{Binding Path=TextChangedCommand}"/>
        </i:EventTrigger>
    </i:Interaction.Triggers>
        </TextBox>
    </StackPanel>
    

    This might help you.... :)