I'm trying to create a user control that has a Grid with two rows.
the first row for a title and the second one for a content that will be defined outside the user control such as a Button in our example.
Somehow I didn't get it to work.
UserControl1 xaml:
<Grid Background="LightBlue">
<Grid.RowDefinitions>
<RowDefinition Height="50" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<TextBlock Text="Title" FontSize="30" Margin="10,0,0,0"/>
</Grid>
MainWindow xaml:
<Grid>
<local:UserControl1>
<Button>Click me</Button>
</local:UserControl1>
</Grid>
The picture below should explain what's my problem:
The following code
<local:UserControl1>
<Button>Click me</Button>
</local:UserControl1>
Means that you set UserControl1's Content property to be that button. This button simply replaces that UserControls1's markup. So all the things that you have in UserControl1.xaml are not there any more.
EDIT
If you want your UserControl to host some markup that will be set somewhere outside of it, you can add a DependencyProperty to it, for example:
/// <summary>
/// Gets or sets additional content for the UserControl
/// </summary>
public object AdditionalContent
{
get { return (object)GetValue(AdditionalContentProperty); }
set { SetValue(AdditionalContentProperty, value); }
}
public static readonly DependencyProperty AdditionalContentProperty =
DependencyProperty.Register("AdditionalContent", typeof(object), typeof(UserControl1),
new PropertyMetadata(null));
And add some element to it's markup to host that additional content. Here's an example extending the markup you provided:
<UserControl ... Name="userControl">
<Grid Background="LightBlue">
<Grid.RowDefinitions>
<RowDefinition Height="50" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<TextBlock Text="Title" FontSize="30" Margin="10,0,0,0"/>
<ContentPresenter Content="{Binding AdditionalContent, ElementName=userControl}" />
</Grid>
</UserControl>
Now you can use it as following:
<local:UserControl1>
<local:UserControl1.AdditionalContent>
<Button>Click me</Button>
</local:UserControl1.AdditionalContent>
</local:UserControl1>
You have to set the ControlTemplate:
<UserControl>
<UserControl.Resources>
<Style TargetType="{x:Type local:UserControl1}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:UserControl1}">
<Grid Background="LightBlue">
<Grid.RowDefinitions>
<RowDefinition Height="50" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<TextBlock Grid.Row="0" Text="Title" FontSize="30" Margin="10,0,0,0"/>
<ContentPresenter Grid.Row="1" />
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</UserControl.Resources>
</UserControl>
You can template the user control to add additional visuals like the TextBlock.
<UserControl>
<UserControl.Style>
<Style TargetType="{x:Type UserControl}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate>
<Grid Background="LightBlue">
<Grid.RowDefinitions>
<RowDefinition Height="50" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<TextBlock Text="Title" FontSize="30" Margin="10,0,0,0"/>
<ContentPresenter Grid.Row="1" Content="{TemplateBinding Content}" />
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</UserControl.Style>
<Button>
Click me!
</Button>
</UserControl>
Use template with
< ContentControl />
Instead of using Content Presenter
So place this:
<UserControl.Style>
<Style TargetType="{x:Type UserControl}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type UserControl}" >
<Grid Background="LightBlue">
<Grid.RowDefinitions>
<RowDefinition Height="50" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<TextBlock Text="Title" FontSize="30" Margin="10,0,0,0"/>
<ContentControl Grid.Row="1" Content="{TemplateBinding Content}" />
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</UserControl.Style>
to your userControl
This is the simple general template for a user control (without using styles or properties to set the content):
<UserControl ...>
<UserControl.Template>
<ControlTemplate TargetType="{x:Type UserControl}">
<!-- control contents here -->
<ContentPresenter/><!-- outside contents go here -->
<!-- control contents here -->
</ControlTemplate>
</UserControl.Template>
</UserControl>
The <ControlTemplate> represents the user control's XAML duplicated for each control.
The <ContentPresenter> is where the Content gets put when consuming the control.
Related
I am trying to display something like a score board, with team name in top 25% of a square and score taking up lower 75% (with font ratios as appropriate). I also want these controls to grow/shrink as the window gets resized.
To do this I have created a grid and split it into * and 3* rows. I have added one TextBlock to the top row and another TextBlock spanning bottom 4 rows. Then I have wrapped each TextBox in a ViewBox
This causes an application to go into a "break mode".
This shows the issue:
<Window x:Class="WpfRandoms.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfRandoms"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="3*"/>
</Grid.RowDefinitions>
<ListView ItemsSource="{Binding Teams}" HorizontalAlignment="Center" Grid.Row="0" BorderBrush="{x:Null}" Background="{x:Null}">
<ListView.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal" />
</ItemsPanelTemplate>
</ListView.ItemsPanel>
<ListView.ItemContainerStyle>
<Style TargetType="{x:Type ListViewItem}">
<Setter Property="Background" Value="Transparent" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ListViewItem}">
<ContentPresenter />
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ListView.ItemContainerStyle>
<ListView.ItemTemplate>
<DataTemplate>
<Border Margin="10" Padding="10" CornerRadius="5" Width="{Binding Path=ActualHeight, RelativeSource={RelativeSource Self}}">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="3*" />
</Grid.RowDefinitions>
<Viewbox Grid.Row="0">
<TextBlock Text="{Binding Name}" TextAlignment="Center" />
</Viewbox>
<Viewbox Grid.Row="1">
<TextBlock Text="{Binding Score}" FontSize="40" TextAlignment="Center" />
</Viewbox>
</Grid>
</Border>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Grid>
</Window>
With code-behind:
using System.Collections.Generic;
using System.Windows;
namespace WpfRandoms
{
public partial class MainWindow : Window
{
public class Team
{
public string Name { get; set; }
public int Score { get; set; }
}
public IList<Team> Teams { get; private set; }
public MainWindow()
{
InitializeComponent();
Teams = new List<Team>();
Teams.Add(new Team() { Name = "Team A", Score = 78 });
Teams.Add(new Team() { Name = "Team B", Score = 1 });
Teams.Add(new Team() { Name = "Team C", Score = 101 });
DataContext = this;
}
}
}
This seems to be caused by the StackPanel used as ItemsPanelTemplate of a ListView (without this StackPanel everything works fine but the layout is not as desired). However, I am not aware of another way of making ListView horizontal, so I am stuck with the StackPanel.
After some experimenting and reading about how ViewBox works, and how StackPanels behave I arrived at some solution (possibly not the best one).
I am wrapping my ListView in a Border, and then binding the height of a Border within the ListView's DataTemplate to the height of that outside Border.
Because of that there is a small limitation - mainly top/bottom margins cause the elements of the ListView to be trimmed. To avoid this trimming I have added padding to the Border within the DataTemplate, and then added a smaller Border within that has a background etc.
I had to also hide the vertical scrollbar of the ListView.
Here is what I have:
<Window x:Class="WpfRandoms.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="3*"/>
</Grid.RowDefinitions>
<Border x:Name="MyBorder" Margin="10" Grid.Row="0">
<ListView ItemsSource="{Binding Teams}" HorizontalAlignment="Center" VerticalAlignment="Stretch" BorderBrush="{x:Null}" Background="{x:Null}" ScrollViewer.VerticalScrollBarVisibility="Hidden">
<ListView.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</ListView.ItemsPanel>
<ListView.ItemContainerStyle>
<Style TargetType="{x:Type ListViewItem}">
<Setter Property="Background" Value="Transparent" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ListViewItem}">
<ContentPresenter />
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ListView.ItemContainerStyle>
<ListView.ItemTemplate>
<DataTemplate>
<Border Margin="10, 0" Padding="10" Height="{Binding ActualHeight, ElementName=MyBorder}" Width="{Binding Path=ActualHeight, RelativeSource={RelativeSource Self}}">
<Border Background="AliceBlue" CornerRadius="5">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="3*" />
</Grid.RowDefinitions>
<Viewbox Grid.Row="0">
<TextBlock Text="{Binding Name}" TextAlignment="Center"/>
</Viewbox>
<Viewbox Grid.Row="1">
<TextBlock Text="{Binding Score}" FontSize="40" TextAlignment="Center"/>
</Viewbox>
</Grid>
</Border>
</Border>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Border>
</Grid>
</Window>
If there is a better solution, I would greatly appreciate it :)
I'm not sure if I understand your problem exactly. If you are looking to keep the ratios between the name and score the same, you can use the "*" for the name (25%) and "3*" for the score (75%). You can also put each TextBlock in a Viewbox rather than the entire thing. To keep it simple, I replaced the converter and bindings with hard coded strings.
<Window x:Class="WpfApplication1.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">
<Grid>
<Border Margin="10" Padding="10" CornerRadius="5" Background="Coral">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="3*" />
</Grid.RowDefinitions>
<Viewbox Grid.Row="0">
<TextBlock Text="Home" TextAlignment="Center" />
</Viewbox>
<Viewbox Grid.Row="1" >
<TextBlock Grid.Row="1" Text="25" TextAlignment="Center" />
</Viewbox>
</Grid>
</Border>
</Grid>
I think you may have a problem with the converter you are referencing on the boarder control.
I tested your XAML without the bindings and the view box works as expected.
<Border Margin="10" Padding="10" CornerRadius="5" Width="{Binding Path=ActualHeight, RelativeSource={RelativeSource Self}}">
<Viewbox>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<TextBlock Text="Team Name" TextAlignment="Center" Grid.Row="0" />
<TextBlock Text="100" FontSize="100" TextAlignment="Center" Grid.Row="1" Grid.RowSpan="3"/>
</Grid>
</Viewbox>
</Border>
Hopefully this helps!
I want to override the default template but i have trouble implementing it.
I tried this:
<charting:Chart Title="{Binding Title}" Name="chChart" LegendStyle="{StaticResource LegendStyle1}">
<charting:Chart.Axes>
<charting:DateTimeAxis
x:Name="Abcisa"
Orientation="X"
ShowGridLines="True"
Title="{Binding Abscissa}">
<charting:DateTimeAxis.Template>
<ControlTemplate TargetType="{x:Type charting:DateTimeAxis}">
<Grid x:Name="AxisGrid">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<!--generate content for x axis-->
<datavis:Title x:Name="AxisTitle" Grid.Row="1" />
</Grid>
</ControlTemplate>
</charting:DateTimeAxis.Template>
</charting:Chart>
But i got this for visual tree:
What should i do to create template for DateTimeAxis control?
You should set the Style property of the Title to the TitleStyle of the Axis. This is what the default template looks like:
<ControlTemplate TargetType="charting:DateTimeAxis">
<Grid x:Name="AxisGrid" Background="{TemplateBinding Background}">
<datavis:Title x:Name="AxisTitle" Style="{TemplateBinding TitleStyle}" />
</Grid>
</ControlTemplate>
But you also need to add some data series to the chart for the axis to show up. Please refer to the following article for more information about this and an example: https://www.codeproject.com/Articles/196502/WPF-Toolkit-Charting-Controls-Line-Bar-Area-Pie-Co
As in my last question I'm about to re-create an expander + it's toggle button.
Expander Template:
<ControlTemplate TargetType="Expander">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="15"/>
</Grid.RowDefinitions>
<ContentPresenter x:Name="ContentPresenter" Grid.Row="0"/>
<ToggleButton Grid.Row="1" >
....
</ToggleButton>
</Grid>
Now when I use this Custom Control in my Main View and add a Control (e.g. a Button):
<custom:FullWidthExpander Width="200" HeaderBackground="Gray">
<Button />
</custom:FullWidthExpander>
The ToggleButton (which is defined in my Expander Template above) gets overridden by this Button.
Are you binding the UserControl.Content to the Expander.Content property?
<!-- define a custom Template for the UserControl FullWidthExpander -->
<UserControl.Template>
<ControlTemplate TargetType="UserControl">
<!-- be sure to include the Content binding to pass the UC.Content to Expander -->
<Expander Content="{TemplateBinding Content}">
<!-- create a custom Template for this Expander -->
<Expander.Template>
<ControlTemplate TargetType="Expander">
<Grid>
<Grid.RowDefinitions>
<RowDefinition x:Name="ContentRow" Height="*"/>
<RowDefinition Height="20"/>
</Grid.RowDefinitions>
<ContentPresenter Grid.Row="0" Content="{TemplateBinding Content}"/>
<ToggleButton Grid.Row="1" Content="Test Toggle Button" />
</Grid>
</ControlTemplate>
</Expander.Template>
</Expander>
</ControlTemplate>
</UserControl.Template>
I did a quick test, and this works fine when using the control like this :
<local:FullWidthExpander>
<Button Content="Test Content Button"/>
</local:FullWidthExpander>
I also took a look at your other question, and if you have your ControlTemplate.Triggers here then you will also want to make sure to set Expander.IsExpanded to True in order to view your Content. Your trigger is hiding the top content row if IsExpanded=False, which is the default for an Expander.
When you do this, it means that the entire contents of the user control is replaced with the content you provided.
<custom:FullWidthExpander Width="200" HeaderBackground="Gray">
<Button />
</custom:FullWidthExpander>
To get around this you need to host the content little bit differently in your usercontrol
First add a dependency property for the user control
public object UserControlContent
{
get { return (object)GetValue(UserControlContentProperty); }
set { SetValue(UserControlContentProperty, value); }
}
public static readonly DependencyProperty UserControlContentProperty =
DependencyProperty.Register("UserControlContent", typeof(object), typeof(FullWidthExpander),
new PropertyMetadata(null));
Then bind this to the contentpresenter in the usercontrol's xaml also define a name for your usercontrol like x:Name="Root".
<Expander Header="My expander header">
<Expander.Template>
<ControlTemplate>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="15"/>
</Grid.RowDefinitions>
<ContentPresenter x:Name="ContentPresenter" Grid.Row="0" Content="{Binding UserControlContent, ElementName=Root}" />
<ToggleButton Grid.Row="1" Content="Togglebutton">
</ToggleButton>
</Grid>
</ControlTemplate>
</Expander.Template>
</Expander>
And finally you define the content content in maindwindow xaml as such
<custom:FullWidthExpander>
<custom:FullWidthExpander.UserControlContent>
<Button Content="Click me"/>
</custom:FullWidthExpander.UserControlContent>
</custom:FullWidthExpander>
I have a custom WindowStyle, the XAML looks like this:
<Style TargetType="{x:Type Window}"
x:Key="WindowStyle">
/** Some setters **/
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ContentControl">
<AdornerDecorator>
<Grid Background="#88000000"
x:Name="WindowBackgroundGrid">
<Border x:Name="WindowContentBorder"
Background="{DynamicResource WindowBackground}"MaxHeight="{Binding Source={x:Static SystemParameters.FullPrimaryScreenHeight}}"
MaxWidth="{Binding Source={x:Static SystemParameters.FullPrimaryScreenWidth}}"
Margin="20">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<!-- Header -->
<Border BorderBrush="{DynamicResource BorderBrushColor}"
Background="{DynamicResource PaneHeader_Background}"
Grid.Row="0">
<TextBlock Text="Title"Foreground="{DynamicResource DefaultForeground}"
FontSize="16"
FontWeight="Bold"
Margin="5,5,2,5" />
</Border>
<!-- Content -->
<ScrollViewer Grid.Row="1"
Margin="5">
<ContentPresenter Content="{TemplateBinding Content}" />
</ScrollViewer>
</Grid>
</Border>
</Grid>
</AdornerDecorator>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
Now I want the inner Grid in a seperate Style so that I can use it elsewhere.
<Style x:Key="WindowContentStyle"
TargetType="{x:Type ContentPresenter}">
<Setter Property="ContentTemplate">
<Setter.Value>
<DataTemplate>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<!-- Header -->
/** Border control **/
<!-- Content -->
<ScrollViewer Grid.Row="1"
Margin="5">
<ContentPresenter Content="{Binding Content, RelativeSource={RelativeSource TemplatedParent}}" />
</ScrollViewer>
</Grid>
</DataTemplate>
</Setter.Value>
</Setter>
</Style>
And I use a ContenPresenter in my WindowStyle to present it:
<ContentPresenter>
<ContentPresenter.Style>
<Style TargetType="{x:Type ContentPresenter}"
BasedOn="{StaticResource WindowContentStyle}" />
</ContentPresenter.Style>
</ContentPresenter>
Problem
The edit above didn't give me any errors, but it doesn't present my WindowContentStyle.
When I set the Content property of the Window control and load the style
this.window.Content = view;
this.window.Style = (Style)Application.Current.TryFindResource("WindowStyle");
the content is shown in the ContentPresenter in the WindowStyle and not in WindowContentStyle. Because of this, the Template is not used and I don't have a header with a title.
How can I make my outer ContentPresenter pass on the Content to my inner ContentPresenter (the one in WindowContentStyle)?
Thanks in advance!
Greetings
Loetn
You should use a ContentControl to display your content, not a ContentPresenter. From the ContentPresenter Class page on MSDN:
You typically use the ContentPresenter in the ControlTemplate of a ContentControl to specify where the content is to be added.
From the ContentControl Class page on MSDN:
A ContentControl has a limited default style. If you want to enhance the appearance of the control, you can create a new DataTemplate.
I have customized TreeView in usercontrol.
In the HierarchicalDataTemplate I have an image with direction (arrow for the example).
When the application\UserControl flow direction change I need to flip the image.
So i tried binding the Image.FlowDirection (Which is flipping the image automatic when RightToLeft) to the UserControl.FlowDirection
<Image FlowDirection="{Binding Path=FlowDirection,
ElementName=MyUserControl}" ... />
But it is not working. I guess because he can't find the UserControl from inside the template.
I've tried this binding outside the template - and it's working fine.
Any solution ?
How can I get my UserControl from inside the template ?
--UPDATE--
There are two places of binding in this xaml. The first is in the style of the button, and it is working, and the second in the template of the TreeViewItem - and there it's not working.
<UserControl x:Class="MyTree"
...
d:DesignHeight="218" d:DesignWidth="284" x:Name="MyLayerListControl">
<UserControl.Resources>
<Style x:Key="CloseButtonStyle" TargetType="Button">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Grid>
<VisualStateManager.VisualStateGroups>
...
</VisualStateManager.VisualStateGroups>
<Border x:Name="CloseButtonBorder" BorderThickness="0" Margin="3" CornerRadius="0" Background="Gray" >
<!-- THIS BINDING IS WORKING -->
<Image Source="{StaticResource back}" Margin="2"
FlowDirection="{Binding Path=FlowDirection, ElementName=MyLayerListControl}"/>
</Border>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</UserControl.Resources>
<Grid x:Name="LayoutRoot" Background="Transparent">
<Button Style="{StaticResource CloseButtonStyle}" />
<Grid>
<Grid.ColumnDefinitions></Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"></RowDefinition>
<RowDefinition Height="*"></RowDefinition>
</Grid.RowDefinitions>
<Grid.Resources>
<sdk:HierarchicalDataTemplate x:Key="LayerListTemplate" ItemsSource="{Binding Path=Childrens}" >
<Grid>
<Border CornerRadius="2" BorderBrush="#FF6DBDD1" BorderThickness="1" Background="#FFBADDE9" Opacity="0.5" />
<StackPanel Orientation="Vertical">
<!-- The Item -->
<StackPanel Orientation="Horizontal" Margin="3">
<!-- THIS BINDING IS NOT WORKING -->
<Image x:Name="ArrowImage" Width="16" Height="16" Source="{StaticResource arrow}"
FlowDirection="{Binding Path=FlowDirection, ElementName=MyLayerListControl}"/>
</StackPanel>
</StackPanel>
</Grid>
</sdk:HierarchicalDataTemplate>
</Grid.Resources>
<sdk:TreeView ItemsSource="{Binding}" ItemTemplate="{StaticResource LayerListTemplate}" x:Name="MyTreeView" Grid.Row="1" />
</Grid>
</Grid>
</UserControl>
As #Chris says, add "DataContext" in front of you binding path, as you are binding to the Control itself, so if FlowDirection is a property of the DataContext, you need to have that.
Also, make sure you have Mode=TwoWay in your binding.
As an alternative, you can you use RelativeSource so you don't have to hard code an ElementName.
Check out: http://tonychampion.net/blog/index.php/2011/12/7th-day-of-silverlight-ancestor-relative-source-binding/