Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract simple wpf markup to usercontrol with databinding of VM

I feel dumb for having to ask this but I've been reading both Microsoft and non-Micorosoft documentation all weekend and it all is either far to simplistic, or covering some strangely esoteric cases that are not relevant to me.

What I need is very simple. I have some markup

            <Viewbox Grid.Row="1" Margin="55,3,15,0">
                <Grid>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="303*"></ColumnDefinition>
                        <ColumnDefinition Width="156*"></ColumnDefinition>
                    </Grid.ColumnDefinitions>
                    <TextBlock Grid.Column="0" Text="{Binding TextSettings.PlayerNumber}" />
                    <TextBlock Grid.Column="1" Text="{Binding PlayerNumber}" />
                </Grid>
            </Viewbox>

For a variety of reasons I want the contents of that viewbox to live in another file. It doesn't even have to be re-usable, It just has to be in a UserControl that I can either include, or not include, or include a different one based on application state.

What I can't figure out is how to move that Grid into is own UserControl and have the bindings continue working. I assume that I would have to pass the ViewModel from the parent view into the child via a parameter, but for the life of me I cannot find an example of the correct syntax.

So. If that was to be moved to its own UserControl,

  1. What would the UserControl look like?
  2. What would I need to add to the UserControl's codebehind ot get the binding working?
  3. What would the inclusion point look like?
like image 941
George Mauer Avatar asked Apr 11 '16 00:04

George Mauer


1 Answers

Your data context will be inherited down the visual tree. So just define your UserControl

<UserControl x:Class="WpfApplication1.MyUserControl"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
         mc:Ignorable="d" 
         d:DesignHeight="300" d:DesignWidth="300">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="303*"></ColumnDefinition>
            <ColumnDefinition Width="156*"></ColumnDefinition>
        </Grid.ColumnDefinitions>
        <TextBlock Grid.Column="0" Text="{Binding TextSettings.PlayerNumber}" />
        <TextBlock Grid.Column="1" Text="{Binding PlayerNumber}" />
    </Grid>
</UserControl>

Then in your parent window you will need to declare the namespace of the user control:

xmlns:local="clr-namespace:WpfApplication1" 

Then use it:

<Viewbox Grid.Row="1" Margin="55,3,15,0">
    <local:MyUserControl/>
</Viewbox>
like image 149
James Durda Avatar answered Sep 22 '22 05:09

James Durda