Craig
Craig

Reputation: 31

WPF MVVM Control Templates (grouping of two or more controls) inc bindings

Please can someone advise on how to implement the following?

I am building an application in WPF via the MVVM design pattern and I am having to create multiple views, many of which have identical controls, such as a button and TextBlock horizontally within a StackPanel. The button selection allows the user to select a file, and the TextBlock displays the filename of said selected file.

I am wanting to create some type of template?, unsure which, there appear to be so many, control, data, user etc. that i can re-use in multiple views, or even multiple times on the same view and here lies the complication.

So, I'm trying the ControlTemplate, add my Button and TextBlock but i must be able to set the CommandParameter, Content and Text properties from the parent object using TemplateBinding, but things like Text="{TemplateBinding Text}" isnt an option.

This is what i've tried

<ControlTemplate x:Key="ButtonAndTextBlock" TargetType="ContentControl">
        <Grid Height="40" >
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="Auto"/>
                <ColumnDefinition Width="*"/>
            </Grid.ColumnDefinitions>
            <Button  Command="{Binding ButtonCommand}" CommandParameter="{TemplateBinding Content}" Content="{TemplateBinding Content}"  />
            <TextBlock Text="{TemplateBinding Content}" Grid.Column="1" Margin="10,0" Foreground="White" VerticalAlignment="Center"/>
        </Grid>
    </ControlTemplate>

If in my view I set Content as follows, then the button text, textblock and commandparameter are all set to "Select xml file...", as expected. I could change these so one is Content, one is Tag and one is say ToolTip but that feels so wrong!

 <ContentControl Content="Select xml file..." Template="{StaticResource ButtonAndTextBlock}" /> 

If i change Content to Content="{Binding contentValue}" then how can I re-use this control multiple times within the same view as contentValue will be binded to multiple places.

Ultimately, all I want is to create a little multi purpose re-useable control containing Button and TextBlock and be able to control some properties from the parent ContentControl where I call the Template and be able to re-use it multiple times to save me re-writing the same xaml in multiple views. What am I missing. Even just a pointer in the right direction would be great. Happy to go read the material as long as i know what I should be reading.

Whatever I use, ContentControl, DataTemplate, UserControl I seem to be lacking in knowledge as to how I can modify the values via binding.

Any help is greatly appreciated.

Thanks

Upvotes: 0

Views: 201

Answers (0)

Related Questions