Extremely confused about ContentPresenter - windows

FYI I'm pretty new to Silverlight.
Okay, so I want to build a simple user control that contains a button plus some additional XAML as specified by the client of the control.
I got searching on Google and found at least 30 different articles that were all very confusing; especially because they talk about styling animation, customizing other controls that you don't own, and other crap I'm not ready for yet.
This is what I did.
In VS 2010, I right clicked and added a new UserControl called MyControl
To the MyControl.xaml I changed the LayoutRoot to a StackPanel and added a Button inside it
In my MainPage.xaml I added an instance of MyControl
I added a TextBox as a child element of this instance
I tried to build and got an error that MyControl didn't support Direct Content
Googled some more..
I changed MyControl to inherit from ContentControl and updated the xaml
I added a ContentPresenter in the xaml to represent the client "custom content"
Okay, it builds and the TextBox shows up, but the Button is missing.
Here's the relevant section from MainPage.xaml
<my:MyControl HorizontalAlignment="Left" Margin="49,26,0,0" x:Name="myContentControl1" VerticalAlignment="Top" Height="550" Width="389">
<TextBox Height="72" HorizontalAlignment="Left" Margin="166,339,0,0" Name="textBox1" Text="TextBox" VerticalAlignment="Top" Width="460" />
</my:MyControl>
Here's the MyControl.xaml
<ContentControl x:Class="ContentControlTest.MyControl"
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"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
d:DesignHeight="480" d:DesignWidth="480">
<StackPanel x:Name="LayoutRoot" Background="{StaticResource PhoneChromeBrush}" Orientation="Vertical">
<ContentPresenter/>
<Button Content="Button" Height="72" HorizontalAlignment="Left" Margin="78,254,0,0" Name="FooFoo" VerticalAlignment="Bottom" Width="160" />
</StackPanel>
</ContentControl>
And here is the MyControl.cs
using System.Windows.Controls;
namespace ContentControlTest
{
public partial class MyControl : ContentControl
{
public MyControl()
{
InitializeComponent();
}
}
}
The way I thought it worked was that the child elements of the control instance are set as the Content property on the ContentControl base class of MyControl. Then, ContentPresenter "pastes" that content into the MyControl.xaml wherever appears.
Although that does seem to be how it works, in the process it is "eating" the Button that I have defined in the MyControl.xaml.
I'm trying not to get into ControlTemplate etc that at this point unless it is absolutely necessary.
Can someone with a clue please tell me what I am doing wrong.
thanks!

That's because the Content of the control is the entire StackPanel you've written by hand; when you set a new Content, the StackPanel is replaced.
A ControlTemplate is necessary for this scenario, I think; it would be a very simple one after all. The starting point can be the default style of the content control; put the style inside a ResourceDictionary (for instance, in the <ContentControl.Resources> section of your user control), and you're ready to go; all you need to do is add a grid and button inside that template.
Note that the style I linked to sets itself as the default for any reachable ContentControl; to make it only apply to your control and not to any children that may appear inside it, add x:Key="someKey" to the Style and set the ContentControl's Style property explicitly to Style={StaticResource someKey}.
Let me know if you need additional information; also, I might be wrong and there may be an easier way, but I doubt it; the Content property is meant to behave exactly like what you described.

Related

Visual Studio "Auto" width / height in XAML-Designer

I'm trying to build a UserControl in a UWP application and I'm not able to see its "Auto" size (based on its content) in the XAML-Designer.
I'm aware I can hardcode d:DesignHeight and d:DesignWidth to absolute values, but since the size should be based on its content, I don't want to hardcode the values.
Is there something like d:DesignHeight="Auto" / d:DesignWidth="Auto" ?
E.g. - for the sample User Control below
<UserControl
x:Class="MyCompany.UserControls.MyUserControl1"
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:local="using:MyCompany.UserControls.UserControls"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<StackPanel>
<Button Content="First" />
<Button Content="Second" />
</StackPanel>
</UserControl>
I'm seeing
However I'd like to see the size of the control based on its content.
Unfortunately, this is a limitation of the XAML designer. The control will still be sized properly at runtime.
However, this is a very good feedback and I suggest you send it as enhancement request in through Visual Studio feedback, I would definitely upvote it :-) .
If delete d:DesignHeight & d:DesignWidth in user control, it will layout as to it's content.
if it doesn't, then you can add VerticalAlignment & HorizontalAlignment to your user control while using.
<local:MyUserControl2 VerticalAlignment="Top" HorizontalAlignment="Left"
BorderBrush="Red" BorderThickness="1"/>
It should work.

Xamarin Custom Control Command / CommandParameter question

I've been working on creating a custom control for some time. After several iterations I've come to the conclusion that I am having a binding issue... As it is, when I place my control into a simple XAML page and execute the feature, it works just fine. However, when I need to instantiate numerous controls on a single page, i.e. into a collection, flexlayout, carouselview the Command and CommandParameter bindings get lost... and the ViewModel calls no longer occur.
My control is simple... think of a checkbox replacement. I place A 1x1 grid, with a frame (for the outline) and a label to place a single character... "A", "B", "C"... "1". "2". "3"... whatever you would require... I have bindable properties.. Text, TextColor, BorderColor, BackgroundColor, and "Selected".
So, now I need to have a page ask the question... "How do you feel about... whatever... Pick all that apply." Then I provide a list... with number or lettered items... The user can select none, any, or all... So I create a view with a series of questions, that have a list of "checkable" items... As I said above, the control works perfectly if it is in a standalone page... If I generate a List of these controls dynamically, Command and CommandParameter suddenly no longer work.
my test implementation looks something like the following... although in this case think something much simpler like a "lottery ticket" number chooser. In this case the ViewModel would have a simple ObservableCollection<string> PrimaryControlList; And, the CommandParamter will call a VM function along with the text of the control in order to track the items the user has selected.
<Frame x:Name="primaryFrame">
<FlexLayout x:Name="flexPrimary" BindableLayout.ItemsSource="{Binding PrimaryControlList}" Wrap="Wrap" Direction="Row" JustifyContent="SpaceAround" AlignItems="Start" AlignContent="Start" >
<BindableLayout.ItemTemplate>
<DataTemplate>
<local:NumberSelect Text="{Binding .}" Command="Binding DoSomethingWithThis" CommandParameter="{Binding .}"/>
</DataTemplate>
</BindableLayout.ItemTemplate>
</FlexLayout>
</Frame>
Can anyone provide guidance?
The command is in your ViewModel while the current BindingContext of FlexLayout is PrimaryControlList.
Solution:
First, give a name to your ContentPage, let's say it MyPage:
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:d="http://xamarin.com/schemas/2014/forms/design"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
x:Name="MyPage"
x:Class="App266.MainPage">
Assume your page binds to a ViewModel and your binding of command should be:
<local:NumberSelect Text="{Binding .}" Command="{Binding BindingContext.ButtonCommand, Source={x:Reference MyPage}}" CommandParameter="{Binding .}"/>

WP7: Listbox item template doesn't work when edited?

**UPDATED**
Just something quick, hope you guys can help me but i'm having this problem where I open up my wp7 project in blend and i edit the listbox item template and i finish it but. I save everything and go back to VS2010 for Windows phone and hit debug but i look at the phone and i have no items showing up at all. The listbox is just blank.
Code:
<ListBox toolkit:TiltEffect.IsTiltEnabled="True" x:Name="ListBox1" FontSize="42.667" FontFamily="Segoe WP SemiLight" IsSynchronizedWithCurrentItem="False" d:LayoutOverrides="VerticalAlignment">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel x:Name="sp">
<toolkit:ContextMenuService.ContextMenu>
<toolkit:ContextMenu IsZoomEnabled="False" >
<toolkit:MenuItem Header="Delete" Click="Delete_Click" Name="MenuItem1" />
<toolkit:MenuItem Header="Edit" Click="Edit_Click"/>
<toolkit:MenuItem Header="View" Click="View_Click"/>
<toolkit:MenuItem Header="Share.." Click="Share_Click"/>
</toolkit:ContextMenu>
Quick Brief
The app I'm making is a simple note app which saves notes in to a folder in the isolated storage. It successfully retrieves the items but i just want to make it so that it has the title and a brief description. This is all in one item. I've got to that point and the 2 textblocks have ="{Binding}" this basically just adds the title I'm assuming but i also added the ="{Binding}" to the second textblock so its basically showing the title for both of them. Is there a way to bind it to a specific item? like the second textblock, how can i bind that so that it shows 1st 12 characters inside a text file so basically it just shows the title and a brief description?
Maybe you have designtime-only data?
In case you're using Mvvm Light DataService approach, you define 2 DataServices: one for designtime and another for realtime.
Just random assuming. it would be nice to see some sample.
UPD: you posted wrong code, this one is about ContextMenu. I dont see binding there.
But again, generally talking, there shouldnt be any problems. You just deserialize data into model, say
public class Note
{
public string Name {get; set; }
public string Content; {get; set; }
}
And then you have List (or even ObservableCollection if you want realtime changes like renaming). And then you just bind
<TextBlock Text="{Binding Name}"/>
<TextBlock Text="{Binding Content}"/>
If you want to have a strict limit for Content/Description of 12 characters, you can add either Converter and take only 12 first characters, or introduce new property
class Note
{
***
public string Description { get { return Content.Substring(0, 12); } }
}
UPD2:
Ok, lets start from the very beginning. First, MVVM is recommended pattern for Wp7 applications. I believe, you can google info about it yourself, but here are the most important parts:
Model. Keeps your data (in your case, it is notes names and description).
ViewModel. This is abstract view. You have all logic here, you have all data prepared to be rendered here, but VM have no idea how to render data. In your case, a list of notes would be here.
View. Here is description of your ui. In your case, ListBox would be here.
So, first, make a new project, then use NuGet to install latest Mvvm Light (for example). After installing, you should see folders for viewmodels and models.
Create new class Note, like i described before. It would be your model.
Now, go to viewmodel. In a constructor, add a list of Notes there, call it ListOfNotes. Add manually several items to the list and initialize them (add some random values for Names and Contents fields).
Now, go to view. In the top of the file, there should be something like DataContext = "{Binding MainViewModel, Source={StaticResource ViewModelLocator}}". Inside of the view, add ListBox. It should be something like
<ListBox ItemsSource="{Binding ListOfNotes}" >
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Vertical">
<TextBlock Text="{Binding Name}" />
<TextBlock Text="{Binding Content}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
So, what would happen now. When you would run your app, your view would be initialized. It would get MainViewModel (because is it set as DataContext, in step 4). In the constructor of MainViewModel, a ListOfNotes would be initialized (see step 3). Then, when page would load ListBox, it would try to find ListOfNotes inside of DataContext (MainViewModel in our case). It should find your list of Notes, and then, every element of the ListBox would be associated with every element of your ListOfNotes. As it is described in DataTemplate, it would try to get Note.Name and Note.Content.

How to make repeating textblocks in Windows Phone 7?

Databinding still confues me and I am not sure how to essential make these controls repeat for each bound piece of data I have.
<Grid>
<TextBlock FontSize="25" Text="this is a header"></TextBlock>
<TextBlock Height="30" HorizontalAlignment="Left" Margin="19,36,0,0" Name="txt" Text="line under the header" VerticalAlignment="Top" />
<TextBlock Height="30" FontSize="25" HorizontalAlignment="Left" Margin="306,9,0,0" Name="textBlock2" Text="530" VerticalAlignment="Top" Width="91" />
<TextBlock Height="30" HorizontalAlignment="Left" Margin="305,42,0,0" Name="textBlock3" Text="30" VerticalAlignment="Top" Width="91" />
</Grid>
If my data source would have a count of 50. I would expect to see 50 of these groupings(I probably need to get a scroll bar though).
Not sure how to do this though. I need some sort of datatemplate I guess? Also "line under the header" should be clickable and highlight.
I think you need to use the control named "ItemsControl". Not a derived class, not a ListBox, just plain simple ItemsControl.
Either in code or in XAML, you set the ItemsControl's ItemsSource property to any collection containing your items.
In XAML (either in VS or Blend, to do it WYSIWYG in Blend you must somehow provide design data) you set the ItemsControl's ItemTemplate to a DataTemplate that contains the XAML subtree you want to repeat for every item in your collection.
Inside the DataTemplate, replace "line under the header" with the Button control, with Content="line under the header", and style it however you want. Then, add CallMethodAction to your button. It only takes 2 clicks in Blend, the first one is on "Assets" window. Specify TargetObject="{Binding}" MethodName="actSubtitleClicked". This way, the framework will call the void actSubtitleClicked() method of the item where user clicked the "line under the header".
For best performance, you should also modify the ItemsControl's ItemsPanel template, replacing StackPanel with VirtualizingStackPanel (again, a few clicks in Blend, the first one is the right click, then "Edit additional templates / ItemsPanel / Edit a copy")

Button Styling in XAML

I have customized the button in this way:
<Button BorderBrush="Transparent" Name="DialButton" Click="DialButton_Click" >
<StackPanel Orientation="Horizontal">
<TextBlock FontSize="43" Name="lblNumber" Margin="0,-5,0,0" />
<TextBlock FontSize="12" Margin="5,20,0,0" Name="lblCharacter" />
</StackPanel>
</Button>
Now, when a user presses the button I want the OnPress state to change the color of the labels. I can do this if it's a simple button by changing the Pressed state. But my label is placed inside a stack panel. How can I change the color in this case? Or in which event can I change the colors of the labels from C#.
You can use the PropertyChangeAction in cases like this. You can find this in the behaviors category on the Assets tab in Expression Blend.
Apply this action on the labels. Change the trigger property to the DataTrigger instead of the default EventTrigger. Bind the trigger to the IsPressed property of the DialButton. Add two PropertyChangeActions per TextBlock and set the Value for one of the to true and the other one to false.
Here's an example for one of them. The other is exactly the same.
<TextBlock FontSize="43" x:Name="lblNumber" Margin="0,-5,0,0" Text="25">
<i:Interaction.Triggers>
<ec:DataTrigger Binding="{Binding IsPressed, ElementName=DialButton}" Value="true">
<ec:ChangePropertyAction PropertyName="Foreground">
<ec:ChangePropertyAction.Value>
<SolidColorBrush Color="Red"/>
</ec:ChangePropertyAction.Value>
</ec:ChangePropertyAction>
</ec:DataTrigger>
<ec:DataTrigger Binding="{Binding IsPressed, ElementName=DialButton}" Value="false">
<ec:ChangePropertyAction PropertyName="Foreground">
<ec:ChangePropertyAction.Value>
<SolidColorBrush Color="{StaticResource PhoneForegroundColor}"/>
</ec:ChangePropertyAction.Value>
</ec:ChangePropertyAction>
</ec:DataTrigger>
</i:Interaction.Triggers>
</TextBlock>
If the i: or ec: isn't working, make sure you've got these lines at the top of your xaml file.
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
xmlns:ec="clr-namespace:Microsoft.Expression.Interactivity.Core;assembly=Microsoft.Expression.Interactions"
You'll need to turn this into a custom control and then you can manage the styling of each component based on the state.
Try this in the click event of button
Button butClicked = (Button)sender;
StackPanel panel1 = (StackPanel)butClicked.Content;
var child1Panel1 = panel1.Children[0] as TextBlock;
child1Panel1.Foreground = new SolidColorBrush(Color.FromArgb(255, 18, 18, 18));
If you're only going to use this button once, probably the easiest way would be to open the .xaml file in Expression Blend, and use Blend to customize the button as you wish, including the state change. If you're using the button in more than one place, do as Matt suggested and make it a custom control (which you can also use Blend to design) that you can reuse.

Resources