what is the best way to emulate XAML code inheritance? - wpf

I have a number of UserControl classes:
DataTypeWholeNumber
DataTypeLine
DataTypeDate
DateTypeDuration
etc.
They all inherit from a plain C# class which inherits from UserControl which has no XAML attached to it. I had to do it this way since I was getting errors saying that XAML could not be inherited.
The problem is that the XAML for each of these UserControls is basically the same, so I would like to find some way to at least emulate XAML inheritance so that I don't have to repeat this code for 20 different classes:
<dataTypes:BaseDataType x:Class="TestDependencyProperty827.DataTypes.DataTypeLine"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:dataTypes="clr-namespace:TestDependencyProperty827.DataTypes">
<StackPanel Margin="{Binding Margin}">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="{Binding LabelWidth}"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<StackPanel Grid.Column="0" Orientation="Horizontal">
<TextBlock Text="{Binding Label}" FontSize="14"/>
<TextBlock FontSize="14" Text=":"/>
</StackPanel>
<TextBox Grid.Column="1" FontSize="12" HorizontalAlignment="Left"
Text="{Binding Text}"
Width="{Binding Width}"/>
</Grid>
</StackPanel>
</dataTypes:BaseDataType>
Has anyone run into this problem and found a solution to it?

Use a Style that applies to the base class:
<Style TargetType="BaseClass">
<Setter Property="Control.Template">
<Control.Value>
<StackPanel Margin="{Binding Margin}">
<!-- Rest of code here -->
</Control.Value>
</Style>
Also, I question the need for UserControls for every one of the base types - why can't you just reuse the same UserControl everywhere?

A XAML class can't inherit from a XAML class, but a normal class can inherit from a XAML class - so if the XAML for all of those is the same put that XAML in BaseDataType and crate all the derived types as normal non-WPF c# classes.
If you need to derive other XAML user controls from BaseDataType than this is not possible but you can use styles, data templates or control templates to share the XAML between diffrent controls.

Related

Showing or hiding a control in WPF template based on bindings

I am new to WPF binding/templating. I have some basic questions about a templated TabControl I have as below :
<TabControl x:Name="tcTabs" ItemsSource="{Binding Rooms, UpdateSourceTrigger=PropertyChanged}" Grid.Row="1" Margin="5" BorderThickness="1" IsSynchronizedWithCurrentItem="True">
<TabControl.ItemContainerStyle>
<Style TargetType="TabItem">
<Setter Property="Header" Value="{Binding Name}" />
<Setter Property="ContentTemplate">
<Setter.Value>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="130"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="22"/>
</Grid.RowDefinitions>
<ListBox Grid.Row="0" Grid.Column="0" BorderThickness="0" ItemsSource="{Binding Messages}" DisplayMemberPath="Raw" />
<ListBox Grid.Row="0" Grid.Column="1" BorderThickness="1,0,0,0" BorderBrush="#FFBBBBBB" ItemsSource="{Binding Users}" DisplayMemberPath="Nick" />
<TextBox Grid.Row="1" Grid.ColumnSpan="2" BorderThickness="0,1,0,0" BorderBrush="#FFBBBBBB" Height="22" />
</Grid>
</DataTemplate>
</Setter.Value>
</Setter>
</Style>
</TabControl.ItemContainerStyle>
</TabControl>
The TabControl contains in each tab 2 list boxes and a textbox. One of the listboxes contains user names is is not necessary all the time.
There are 3 kinds of tabs, Server tabs, room tabs and private tabs. In private and server tabs the user list should not exist or be hidden.
I have an enum on the bound room object :
public enum IRCRoomType
{
Server,
Channel,
Private
}
How do I automatically hide the user list based on the enum, I have seen samples of 2 approaches, the binding on visibility with a converter or a trigger. Which is the better approach and are there any more?
When there are no tabs, and the first tab is created it is not automatically selected, how do I select it?
Is there a way of impacting the item styles inside the listboxes depending on tab type? How would I acheive this?
I am just looking for links/hints and not for actual solutions, but if you can give code then that would be a bonus!
It depends on how complicated code. If it's simple I rather use Trigger (you have everything which belows to UI in XAML), but if code is much more complicated consider using Converters (It's actually simpler to use it)
Bind to SelectedIndex of List and set it to 0?
Yes, of course, you can use ContentControl with DataTemplate (Or just DataTemplate in some cases) Some code where I use it:
<ListBox>
<ListBox.Resources>
<DataTemplate DataType="{x:Type your_namespace:your_type}">
... your code ...
</DataTemplate>
<DataTemplate DataType="{x:Type system:String}">
... your code ...
</DataTemplate>
</ListBox.Resources>
</ListBox>
Code you posted is actually a new Template, but you've changed the Style. Please consider override some Template.
Best regards

Partially templated ListBox.ItemTemplate

I'm creating a custom control and I'm trying to create partially specified template for list box items. The template has some predefined parts and there should be another part that can be templated when using the control.
For this I have created a dependency property named SuggestionItemTemplate like so:
public static readonly DependencyProperty SuggestionItemTemplateProperty =
DependencyProperty.Register("SuggestionItemTemplate",
typeof(DataTemplate),
typeof(AutoSuggestTextBox),
new PropertyMetadata(null));
In my custom controls' generic.xaml I have:
<Style TargetType="local:AutoSuggestTextBox">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="local:AutoSuggestTextBox">
<Grid>
<ListBox x:Name="ItemsControl">
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel />
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<ContentPresenter Grid.Column="0"
ContentTemplate="{TemplateBinding SuggestionItemTemplate}"
Content="{Binding}" />
<ToggleButton Grid.Column="1"
x:Name="DetailsHover"
ClickMode="Hover"
Style="{StaticResource DetailsToggleButtonStyle}" />
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
Unfortunatelly, this does not work as it's not possible to use TemplateBinding from inside ContentPresenter nested into DataTemplate. (The member "SuggestionItemTemplate" is not recognized or is not accessible.)
I also tried to use ancestor binding (available in Silverlight 5) like:
<ContentPresenter Grid.Column="0"
ContentTemplate="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=local:AutoSuggestTextBox}, Path=SuggestionItemTemplate}"
Content="{Binding}" />
But this results in binding error:
Error: System.Exception: BindingExpression_CannotFindAncestor
I suppose this happens because I'm inside ControlTemplate of my custom control and "local:AutoSuggestTextBox" is not defined anywhere in the style.
The third option that I tried was to apply ContentTemplate in OnApplyTemplate override but this also doesn't work:
var cp = itemsControlElement.ItemTemplate.LoadContent() as ContentPresenter;
cp.ContentTemplate = SuggestionItemTemplate;
In all cases, I get my grid with two columns, toggle button is visible but content presenter simple prints out view model's type name. (I believe this is the default behavior if the ContentTemplate is null).
Is this even possible to do? Are there any other ways to specify a partial template and then only add customized template part when necessary?
As a workaround for now, I can specify
ItemTemplate="{TemplateBinding SuggestionItemTemplate}"
for the list box and then copy/paste the generic template everywhere I use this control. But this is the behavior I'm hoping to avoid in the first place.
Thanks!
edit: I used the code tags for all blocks of code, but they're not highlighted for some reason. :/
It is possible to walk through Visual Ancestors in the OnApplyTemplate method, find your ContentPresenter(s) and set the ItemTemplate on that. To my mind, this is fine for a single item, but not so much in an ItemsControl scenario.
You could achieve what you are after using your own custom Control. Just give it a Content dependency property of type Object, and a Template DP of type DataTemplate (and multiples of the two if you fancy), and you can set up the root visual style and templates in the default style for your Control.
In this specific case, I would suggest that the best approach is to put your ToggleButton in the ListBoxItem template instead by customising the ListBox.ItemContainerStyle. It is easy to modify the default Control Template using Expression Blend, and the DataContext of the ToggleButton will not change, so the changes to your own logic should be minimal.
Edit: If you mean to use a number of different data templates, perhaps Implicit Data Templates will be more suitable.
I managed to solve this using a different approach. I used ancestor binding but instead of trying to reach the root control (my AutoSuggestTextBox) from the DataTemplate, I ask for a reference to my ListBox (here named ItemsControl).
However, since the ListBox doesn't have the SuggestionItemTemplate property, I sub-classed it to my own CustomListBox where I implemented that property. It all comes down to this code snippet:
<Style TargetType="local:AutoSuggestTextBox">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="local:AutoSuggestTextBox">
<Grid>
<local:CustomizableListBox x:Name="ItemsControl"
SuggestionItemTemplate="{TemplateBinding SuggestionItemTemplate}">
<local:CustomizableListBox.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<ContentPresenter Grid.Column="0"
ContentTemplate="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=local:CustomizableListBox}, Path=SuggestionItemTemplate}"
Content="{Binding}" />
<ToggleButton Grid.Column="1"
x:Name="DetailsHover"
ClickMode="Hover"
Style="{StaticResource DetailsToggleButtonStyle}" />
</Grid>
</DataTemplate>
</local:CustomizableListBox.ItemTemplate>
</local:CustomizableListBox>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>

How come I can only have one instance of a Silverlight UserControl per page?

Its pretty lame, but I tried adding two UserControl's to my Silverlight Page, and I get an exception telling me (with extensive digging) that the same control name has been used to the visual tree twice. So the controls inside my UserControl are named, so therefore I can include only one of this UserControl into the Page at a time. Is this true, or am I not realizing something? Has Microsoft truly given up on code-reuse? This is very lame.
Edits
For people who come here, I was getting this a System.Resources.MissingManifestResourceException exception. It took some time to figure out that the problem was ambiguous names in the visual tree. Hopefully this helps you. Below is the full exception text.
Further Edits
Here is my XAML:
<Grid x:Name="LayoutRoot">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<TextBlock x:Name="HeaderText"
res:Strings.Assignment="Text=MachiningView_Name"/>
<sdk:TabControl Grid.Row="2">
<sdk:TabItem Header="Projects">
<ScrollViewer>
<Grid>
<controls:Organizer Margin="4" ItemsSource="{Binding ProjectSummaries}" Height="24" VerticalAlignment="Top">
<controls:Organizer.GroupDescriptions>
<controls:OrganizerGroupDescription res:Strings.Assignment="Text=NoGroupingText" IsDefault="True" />
<controls:OrganizerGroupDescription res:Strings.Assignment="Text=GroupOwnerEmailText">
<controls:OrganizerGroupDescription.GroupDescription>
<helpers:OwnerEmailGroupDescription />
</controls:OrganizerGroupDescription.GroupDescription>
</controls:OrganizerGroupDescription>
<controls:OrganizerGroupDescription res:Strings.Assignment="Text=GroupStoreNumberText">
<controls:OrganizerGroupDescription.GroupDescription>
<helpers:StoreNumberGroupDescription />
</controls:OrganizerGroupDescription.GroupDescription>
</controls:OrganizerGroupDescription>
</controls:Organizer.GroupDescriptions>
</controls:Organizer>
</Grid>
</ScrollViewer>
</sdk:TabItem>
<sdk:TabItem Header="Machine Queues">
<ScrollViewer>
<Grid>
<controls:Organizer Margin="4" ItemsSource="{Binding ProjectSummaries}" Height="24" VerticalAlignment="Top">
<controls:Organizer.GroupDescriptions>
<controls:OrganizerGroupDescription res:Strings.Assignment="Text=NoGroupingText" IsDefault="True" />
<controls:OrganizerGroupDescription res:Strings.Assignment="Text=GroupOwnerEmailText">
<controls:OrganizerGroupDescription.GroupDescription>
<helpers:OwnerEmailGroupDescription />
</controls:OrganizerGroupDescription.GroupDescription>
</controls:OrganizerGroupDescription>
<controls:OrganizerGroupDescription res:Strings.Assignment="Text=GroupStoreNumberText">
<controls:OrganizerGroupDescription.GroupDescription>
<helpers:StoreNumberGroupDescription />
</controls:OrganizerGroupDescription.GroupDescription>
</controls:OrganizerGroupDescription>
</controls:Organizer.GroupDescriptions>
</controls:Organizer>
</Grid>
</ScrollViewer>
</sdk:TabItem>
</sdk:TabControl>
</Grid>
And here is my user control's XAML:
<StackPanel Orientation="Horizontal" DataContext="{Binding ElementName=UserControl}">
<sdk:Label Content="Page:" VerticalAlignment="Center" Margin="0,0,5,0"/>
<sdk:DataPager Name="_projectSummariesPager"
Margin="0,0,5,0"
DisplayMode="FirstLastPreviousNextNumeric"
Source="{Binding Path=ItemsSource}"
PageSize="10"/>
<ComboBox Name="_itemPerPageCombo"
Margin="0,0,5,0"
SelectionChanged="_itemPerPageCombo_SelectionChanged"
SelectedItem="{Binding Path=SelectedPageSize, Mode=TwoWay}"
SelectedValuePath="Value"
ItemsSource="{Binding Path=PageSizes}"/>
<ComboBox Name="_groupDescription"
Margin="0,0,5,0"
SelectionChanged="_groupDescription_SelectionChanged"
SelectedItem="{Binding Path=SelectedGroupDescription, Mode=TwoWay}"
ItemsSource="{Binding Path=GroupDescriptions}"/>
</StackPanel>
Names given to elements in Xaml need to be unique within the namescope. Each execution of LoadComponent creates a new namescope. Hence the names within the UserControl will not conflict in the visual tree when multiple instances of the control were used.
So the answer to question as it stands right now is: because you are doing something wrong.
What the "something" is is unclear right now. Perhaps if you included your xaml in the question we can help you.
Edit
So reading between the lines this is what I'm guessing you are doing. You have a UserControl that has a number for properties and you want controls within the UserControl to bind to these properties so you are doing this:-
<StackPanel Orientation="Horizontal" DataContext="{Binding ElementName=UserControl}">
This would indicate that you have added Name="UserControl" to the <UserControl.. element at the top of its xaml.
I can't quite find a way to reproduce your problem but I am aware of problems with earlier versions of SL where this approach is a problem. Personally I think its better to avoid setting properties that really belong to the external consumer of the component (its up to the page that is using you UserControl what its name is and whether it should have name at all).
Hence my approach to solve this "Bind to the UserControl itself" sort of Problem:-
<StackPanel Orientation="Horizontal" DataContext="{Binding ElementName=LayoutRoot.Parent}">
where LayoutRoot is the name of the top level Grid which is the root of the UserControl content. This still binds to the UserControl itself via the Grid's Parent property. However this does not require a name to be added to the UserControl itself in its own xaml.
When you add the UserControl, make sure to assign it a unique name, ie:
<Page ...
<StackPanel>
<local:YourUserControl x:Name="Foo" />
<!-- Make sure not to duplicate x:Name/Name here! -->
<local:YourUserControl x:Name="Bar" />
</StackPanel>
</Page>

How do I layout a form in WPF using grid or other controls for maintainability [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I have a WPF form, I want to lay out a standard form onto it. Each form element will have a label, and then a control. Pretty standard stuff.
If I use a wrap panel, it can cause the label and the control to be separated, but I want them to stay together. Is there some WPF equivalent of <nobr/>?
Grid works, and allows for column spanning etc, however I really really hate that you specify the column and row on each control. This makes it extremely inconvenient to reorder or insert things into the list.
Is there a way to get the grid to use more HTML style column/rows where the items are a child of the row they are in, so that I can re-order easily?
Is there some other control that will let me layout a form easily?
is there some WPF equivalent of nobr?
Remember that you can nest panels:
<WrapPanel Orientation="Horizontal">
<StackPanel Orientation="Horizontal">
<Label>Some field</Label>
<TextBox>Some value</TextBox>
</StackPanel>
<StackPanel Orientation="Horizontal">
<Label>Another field</Label>
<TextBox>Another value</TextBox>
</StackPanel>
...
</WrapPanel>
Also, for columnar layouts, the shared size scope of the Grid can coordinate any number of grids that use it:
<StackPanel Orientation="Vertical" Grid.IsSharedSizeScope="True">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" SharedSizeGroup="Label"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Label Grid.Column="0">Some field</Label>
<TextBox Grid.Column="1">Some value</TextBox>
</Grid>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" SharedSizeGroup="Label"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Label Grid.Column="0">Another field</Label>
<TextBox Grid.Column="1">Another value</TextBox>
</Grid>
</StackPanel>
I kind of hate how verbose the XAML for this is, especially that you have to repeat the column definitions. Though if you structure your classes properly and use templates it's not so terrible. And notice that you aren't keep track of row numbers anywhere in this scheme, so reordering fields is simple.
What you might be looking for is a stack panel. Using a vertical StackPanel will allow you to arrange your label and controls consistently. For each label and control you might want a horizontal stack panel like so
<StackPanel Orientation="Vertical">
<StackPanel Orientation="Horizontal">
<Label Width="150">Name</Label>
<TextBox Width="200" />
</StackPanel>
<StackPanel Orientation="Horizontal">
<Label Width="150">Date of Birth</Label>
<DatePicker Width="200" />
</StackPanel>
</StackPanel>
Now you can add, remove, edit, and reorder to your heart's content without worrying about columns and rows.
Try the UniformGrid control.
If you can accord it, I recommend Expression Blend if you are going to be doing much UI design. It allows a simpler view of the items. Nesting controls into various containers is a good way to get the UI to be dynamic, but structured.
Typically I will use a Grid panel to break a window up into functional areas. Then I will use a series of StackPanels (often a vertical stack panel with horizontal StackPanels inside it, each with a label and textbox).
Unfortunately Grids only work as you stated. Elements in them specify the row and/or column that they reside in. If you used Blend, adding Grid Columns or Rows will have controls auto-magically change the row/column specification to stay in the position they were placed.
Hope it helps.
Expression Blend Trial at Microsoft.
UPDATE:
VS2012 has a lot of the Expression Blend functionality baked into the WPF designer. Much of the need for a copy of Blend is no longer there as developers have access to a lot of the cool tools from Blend.
Here is a library for it
Sample xaml:
<UserControl ...
xmlns:autoRowGrid="http://gu.se/AutoRowGrid"
...>
<autoRowGrid:Grid ColumnDefinitions="Auto *">
<autoRowGrid:Row Name="first row">
<TextBlock Text="foo1" />
<TextBox Text="{Binding Value1}" />
</autoRowGrid:Row>
<autoRowGrid:Row Name="second row">
<TextBlock Text="foo2" />
<TextBox Text="{Binding Value2}" />
</autoRowGrid:Row>
</autoRowGrid:Grid>
...
It is a markupextension that returns a vanilla WPF Grid for a nice shallow visual tree.
I came across this post today while having the same question, using the answers in this thread I came up with a manageable solution to simple text/text pairs. To add new fields simply expand the "FormItems" collection.
xmlns:c="clr-namespace:System.Collections;assembly=mscorlib"
<Window.Resources>
<c:ArrayList x:Key="FormItems">
<c:DictionaryEntry Key="First Name" Value="John"/>
<c:DictionaryEntry Key="Last Name" Value="Smith"/>
</c:ArrayList>
</Window.Resources>
<ItemsControl ItemsSource="{StaticResource FormItems}" Grid.IsSharedSizeScope="True">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" SharedSizeGroup="Label"/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<TextBlock>
<Run Text="{Binding Key}"/><Run Text=": "/>
</TextBlock>
<TextBox Grid.Column="1" Text="{Binding Value}"/>
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
There has been no consideration for margins and padding, it just shows the concept of using a DataTemplate to reuse the layout of each item. It can be adapted to include other data types and controls fairly easily. You could even use the ItemTemplateSelector to select a different template based on the type of the DictionaryEntry.Value
EDIT
Another approach that I found that made it easier for DataBinding was to use Visual Studio to create a new WPF "Custom Control". Doing so will create a new file named Themes/Generic.xaml with a new default layout defined there. A few simple edits and we can use the ItemsControl to display our new control.
New class:
public class FormControlItem : ContentControl
{
public object Field {
get { return base.GetValue(FieldProperty); }
set { base.SetValue(FieldProperty, value); }
}
static FormControlItem() {
DefaultStyleKeyProperty.OverrideMetadata(
typeof(FormControlItem),
new FrameworkPropertyMetadata(typeof(FormControlItem)));
}
public static readonly DependencyProperty FieldProperty =
DependencyProperty.Register(
"Field",
typeof(object),
typeof(FormControlItem),
new FrameworkPropertyMetadata());
}
Themes/Generic.xaml:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:MyApplication">
<Style TargetType="{x:Type local:FormControlItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:FormControlItem}">
<Border Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" SharedSizeGroup="Label"/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<ContentPresenter ContentSource="Field"/>
<ContentPresenter Grid.Column="1" ContentSource="Content"/>
</Grid>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
Usage example:
<ItemsControl Grid.IsSharedSizeScope="True">
<local:FormControlItem Field="Name: ">
<TextBox Text="{Binding Path=Name}"/>
</local:FormControlItem>
<local:FormControlItem Field="Type: ">
<ComboBox
SelectedItem="{Binding Path=Type}"
ItemsSource="{Binding Path=TypeValues}"/>
</local:FormControlItem>
<local:FormControlItem Field="Category: ">
<TextBox Text="{Binding Path=Category}"/>
</local:FormControlItem>
</ItemsControl>
Check out Karl's stuff.
http://web.archive.org/web/20150620104259/https://karlshifflett.wordpress.com/2008/10/23/wpf-silverlight-lob-form-layout-searching-for-a-better-solution/
Simple and clean xaml:
<pt:Form x:Name="formMain" Style="{DynamicResource standardForm}" Grid.Row="1">
<TextBox pt:FormItem.LabelContent="_First Name" />
<TextBox pt:FormItem.LabelContent="_Last Name" />
<TextBox pt:FormItem.LabelContent="_Phone" Width="150" HorizontalAlignment="Left" />
<CheckBox pt:FormItem.LabelContent="Is _Active" />
</pt:Form>
In our product we use a HeaderedContentControl to lay out forms in a grid. The control template has a label and padding/margins so that the control's content is always spaced appropriately. In the XAML we just add them down the columns.
I'd post some XAML but I'm in the middle of getting a new computer set up. :| But from what I remember it would look something like this:
<Style x:Key="hccFormStyle" Targettype="{x:Type HeaderedContentControl}>
... some setters for colors, margin, padding, etc...
<Setter Property="Template">
<Setter.Value>
<ControlTemplate>
<Label Content={Binding Content} Target={Binding Tag}> <-- pass the control for the access key with the tag
<ContentPresenter>
</ControlTemplate>
...triggers if necessary - hover states, etc...
</style>
Then in the grid, you define your rows and columns, and put one of these in each cell, or just down each row:
<HeaderedContentControl x:Name="username" Grid.Column=0 Content="User Name" Tag=textboxUserName>
<Textbox x:Name=textboxUserName>
</HeaderedContentControl>
I might be answering a different question but this is how we lay out our forms.
I had the same problem, reordering controls in a Grid based layout is a real pain.
So I've wrote a custom panel that does "form layout" (groups of two columns, all labels same size, all control same size,everything aligned, etc.), it's on my blog at: http://www.nbdtech.com/Blog/archive/2010/07/27/easy-form-layout-in-wpf-part-1-ndash-introducing-formpanel.aspx

Difference between Control Template and DataTemplate in WPF

What is difference between a ControlTemplate and a DataTemplate in WPF?
Typically a control is rendered for its own sake, and doesn't reflect underlying data. For example, a Button wouldn't be bound to a business object - it's there purely so it can be clicked on. A ContentControl or ListBox, however, generally appear so that they can present data for the user.
A DataTemplate, therefore, is used to provide visual structure for underlying data, while a ControlTemplate has nothing to do with underlying data and simply provides visual layout for the control itself.
A ControlTemplate will generally only contain TemplateBinding expressions, binding back to the properties on the control itself, while a DataTemplate will contain standard Binding expressions, binding to the properties of its DataContext (the business/domain object or view model).
Very basically a ControlTemplate describes how to display a Control while a DataTemplate describes how to display Data.
For example:
A Label is a control and will include a ControlTemplate which says the Label should be displayed using a Border around some Content (a DataTemplate or another Control).
A Customer class is Data and will be displayed using a DataTemplate which could say to display the Customer type as a StackPanel containing two TextBlocks one showing the Name and the other displaying the phone number. It might be helpful to note that all classes are displayed using DataTemplates, you will just usually use the default template which is a TextBlock with the Text property set to the result of the Object's ToString method.
Troels Larsen has a good explanation on MSDN forum
<Window x:Class="WpfApplication7.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<DataTemplate x:Key="ButtonContentTemplate">
<StackPanel Orientation="Horizontal">
<Grid Height="8" Width="8">
<Path HorizontalAlignment="Stretch"
Margin="0,0,1.8,1.8"
VerticalAlignment="Stretch" Stretch="Fill" Stroke="#FF000000"
Data="M0.5,5.7 L0.5,0.5 L5.7,0.5"/>
<Path HorizontalAlignment="Stretch"
Margin="2,3,0,0"
VerticalAlignment="Stretch" Stretch="Fill" Stroke="#FFFFFFFF"
Data="M3.2,7.5 L7.5,7.5 L7.5,3.5"/>
<Path HorizontalAlignment="Stretch"
Margin="1.2,1.4,0.7,0.7"
VerticalAlignment="Stretch" Fill="#FFFFFFFF" Stretch="Fill" Stroke="#FF000000"
Data="M2.5,2.5 L7.5,7.5"/>
<Path HorizontalAlignment="Stretch"
Margin="1.7,2.0,1,1"
VerticalAlignment="Stretch" Stretch="Fill" Stroke="#FF000000"
Data="M3,7.5 L7.5,7.5 L7.5,3.5"/>
<Path HorizontalAlignment="Stretch"
Margin="1,1,1,1"
VerticalAlignment="Stretch" Stretch="Fill" Stroke="#FFFFFFFF"
Data="M1.5,6.5 L1.5,1 L6.5,1.5"/>
</Grid>
<ContentPresenter Content="{Binding}"/>
</StackPanel>
</DataTemplate>
<ControlTemplate TargetType="Button" x:Key="ButtonControlTemplate">
<Grid>
<Ellipse Fill="{TemplateBinding Background}"/>
<ContentPresenter HorizontalAlignment="Center"
VerticalAlignment="Center"/>
</Grid>
</ControlTemplate>
</Window.Resources>
<StackPanel>
<Button Template="{StaticResource ButtonControlTemplate}" ContentTemplate="{StaticResource ButtonContentTemplate}" Content="1"/>
<Button Template="{StaticResource ButtonControlTemplate}" ContentTemplate="{StaticResource ButtonContentTemplate}" Content="2"/>
<Button Template="{StaticResource ButtonControlTemplate}" ContentTemplate="{StaticResource ButtonContentTemplate}" Content="3"/>
</StackPanel>
</Window>
(Templates blatently stolen from
http://msdn.microsoft.com/en-us/library/system.windows.controls.controltemplate.aspx
and
http://msdn.microsoft.com/en-us/library/system.windows.controls.contentcontrol.contenttemplate%28VS.95%29.aspx
respectively)
Anyway, the ControlTemplate decides how the Button itself looks, while
the ContentTemplate decides how the Content of the button looks. So
you could bind the content to one of you data classes and have it
present itself however you wanted it.
ControlTemplate: Represents control style.
DataTemplate: Represents data style(How would you like to show your data).
All controls are using default control template that you can override through template property.
For example
Button template is a control template.
Button content template is a data template
<Button VerticalAlignment="Top" >
<Button.Template>
<ControlTemplate >
<Grid>
<Rectangle Fill="Blue" RadiusX="20" RadiusY="20"/>
<Ellipse Fill="Red" />
<ContentPresenter Content="{Binding}">
<ContentPresenter.ContentTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" Height="50">
<TextBlock Text="Name" Margin="5"/>
<TextBox Text="{Binding UserName, Mode=TwoWay}" Margin="5" Width="100"/>
<Button Content="Show Name" Click="OnClickShowName" />
</StackPanel>
</DataTemplate>
</ContentPresenter.ContentTemplate>
</ContentPresenter>
</Grid>
</ControlTemplate>
</Button.Template>
</Button>
public String UserName
{
get { return userName; }
set
{
userName = value;
this.NotifyPropertyChanged("UserName");
}
}
ControlTemplate - Changing the appearance of element. For example Button can contain image and text
DataTemplate - Representing the underlying data using the elements.
ControlTemplate DEFINES the visual appearance, DataTemplate REPLACES the visual appearance of a data item.
Example: I want to show a button from rectangular to circle form => Control Template.
And if you have complex objects to the control, it just calls and shows ToString(), with DataTemplate you can get various members and display and change their values of the data object.
All of the above answers are great but there is a key difference that was missed. That helps make better decisions about when to use what. It is ItemTemplate property:
DataTemplate is used for elements that provide ItemTemplate property for you to replace its items' content using DataTemplates you define previously according to bound data through a selector that you provide.
But if your control does not provide this luxury for you then you still can use a ContentView that can display its content from predefined ControlTemplate. Interestingly, you can change the ControlTemplate property of your ContentView at runtime. One more thing to note that unlike controls with ItemTemplate property, you cannot have a TemplateSelector for this (ContentView) control. However, you still can create triggers to change the ControlTemplate at runtime.

Resources