I have the following custom defined Button defined in my App.xaml file.
<Style x:Key="DispatchListCallButton" TargetType="Button">
<Setter Property="OverridesDefaultStyle" Value="True"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Border Name="outerBorder" BorderThickness="1" BorderBrush="DimGray" CornerRadius="1" Background="{TemplateBinding Background}">
<Border Name="innerBorder" BorderThickness="1" BorderBrush="WhiteSmoke" CornerRadius="1" Background="{TemplateBinding Background}">
<Grid Margin="2">
<Grid.RowDefinitions>
<RowDefinition Height="1*"></RowDefinition>
<RowDefinition Height="2*"></RowDefinition>
<RowDefinition Height="Auto"></RowDefinition>
<RowDefinition Height="1*"></RowDefinition>
</Grid.RowDefinitions>
<StackPanel Orientation="Horizontal">
<TextBlock>2600</TextBlock>
<TextBlock Margin="4,0,0,0">IPRJ</TextBlock>
</StackPanel>
<TextBlock Grid.Row="1" TextWrapping="Wrap">1234 Main St West Avenue</TextBlock>
<Rectangle Grid.Row="2" Height="1" Margin="2,0,2,0" Stroke="DarkGray" />
<StackPanel Grid.Row="3" Orientation="Horizontal" HorizontalAlignment="Right">
<TextBlock>1</TextBlock>
<TextBlock Margin="4,0,0,0">*</TextBlock>
</StackPanel>
<ContentPresenter HorizontalAlignment="Stretch" VerticalAlignment="Center" Name="content"/>
</Grid>
</Border>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
I have left off the triggers since I don’t have issues with them.
This displays exactely what I want, accept that all of the values are currently hard coded. There are a total of 5 TextBlock’s as part of this Button. I would like to be able to set up binding for each of these 5 text blocks so that I can set them dynamically in code behind. Ideally this is what I would like my code behind to look like.
DispatchListCallButton newButton = new DispatchListCallButton();
// Set the 5 TextBlock values
newButton.Id = "4444";
newButton.Code = "ABCD";
newButton.Address = "2000 Main";
newButton.Priority = 5;
newButton.Symbol = "*";
How can I do this and what would the binding expression in the ControlTemplate look like?
You can do this one of two ways.
First Method:
First you would need to create control type that inherited from Button since you cannot modify the button (or instantiate) by the style as you are attempting to now.
You would then define Id,Code,etc. as DependencyProperties of the control. If they are DependencyProperties then the code will automatically register to listen for changes.
Article:
http://msdn.microsoft.com/en-us/library/ms753358.aspx
Second Method:
You would define a ViewModel for the button that exposes those properties and implements INotifyPropertyChange. Each time the propertys are set, fire the event. You would then set newButton.DataContext to an instance of the ViewModel and modify the view model. Bindings would be like Text = {Binding Address}
Article:
http://msdn.microsoft.com/en-us/library/ms229614.aspx