How to reduce margins on buttons inside WrapPanel in WP7? - silverlight

I'm trying to make a 'palette' in WP7. Visually, I'm after a look similar to the keyboard (SIP) or the dialler. I'm trying to make the margins around the buttons smaller than what they are now.
I'm having a lot of trouble with doing this, however - I've tried setting different margin thicknesses both directly and by attaching a style, but can't seem to get the problem sorted.
Here's an image of what I've got at the moment (sorry I'm a new user so it's just a link):
http://i40.tinypic.com/bj8g9f.jpg
And here's the relevant XAML I'm using.
<phone:PhoneApplicationPage
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:tk="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Toolkit"
mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="768"
x:Class="Mathflow.MainPage"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="Portrait" Orientation="Portrait"
shell:SystemTray.IsVisible="True">
<phone:PhoneApplicationPage.Resources>
<Style x:Key="PaletteObjectStyle" TargetType="Button">
<Setter Property="Background">
<Setter.Value>
<SolidColorBrush Color="#1F1F1F"/>
</Setter.Value>
</Setter>
<Setter Property="Margin" Value="0" />
<Setter Property="BorderThickness" Value="0" />
</Style>
<Style x:Key="PaletteObjectText" TargetType="TextBlock">
<Setter Property="Margin" Value="8" />
</Style>
</phone:PhoneApplicationPage.Resources>
<StackPanel x:Name="LayoutRoot" DataContext="">
<Canvas x:Name="FlowContainer" Height="500">
</Canvas>
<ItemsControl x:Name="Palette" DataContext="{Binding Source={StaticResource FunctionsSource}}" ItemsSource="{Binding FunctionCollection}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<tk:WrapPanel Orientation="Vertical" Height="200" ScrollViewer.VerticalScrollBarVisibility="Disabled" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Button Style="{Binding Source={StaticResource PaletteObjectStyle}}">
<TextBlock Text="{Binding Display}" Style="{Binding Source={StaticResource PaletteObjectText}}"/>
</Button>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</StackPanel>
</phone:PhoneApplicationPage>
Thanks very much! Any help would be greatly appreciated.

It appears that the WrapPanel applies a margin to the items it contains. There may be a way to retemplate it to override this, or (more simply) you could just set a negative margin on PaletteObjectStyle.
<Setter Property="Margin" Value="-6" />
You can also simplify your style bindings like this:
<Button Style="{StaticResource PaletteObjectStyle}">
<TextBlock Text="{Binding Display}" Style="{StaticResource PaletteObjectText}"/>

You can try setting Padding to 0. If that does not get you closer to what you need - just replace the entire Template of the button with your own ControlTemplate. You can extract the default template from the button using Blend. Just right click your button and select the option to edit template copy.

Personally I would not use a Button in this case if you are concerned about the Margins.
Instead use a Rectangle and Use the Gesture Lister to watch for the tap event (instead of a click) Only downside of this method is that you cannot use commanding from XAML but you could just launch the command in code if you require it.
See below: (Extract from http://bit.ly/lIleTe)
<Rectangle Fill="Orange" x:Name="rect">
<toolkit:GestureService.GestureListener>
<toolkit:GestureListener Tap="GestureListener_Tap" Hold="GestureListener_Hold" />
</toolkit:GestureService.GestureListener>

Related

Why are ListViewItems within ContentControl only selectable on first few pixels?

I want to request different types of properties from the user of my WPF application. Therefore I have a ListView thats ItemsSource binds to an ObservableCollection<PropertiesBase>. Each property derives from PropertiesBase. As an expert user should be able to edit these properties, the DataTemplate is selected depending on the EditMode Property and the type of the property.
Data display and everything else works fine, except that I am not able to select a ListViewItem. Only when I click a textbox inside a ListViewItem or the first few pixels of the item I am able to select an item.
The selection only works on the white part of the item
I have tried to play around with Focusable but it does not led me to success. I also copied my xaml of the ListViewItem directly into the Listview (without datatemplate). That worked as expected.
ListView XAML:
<ListView ItemsSource="{Binding PropertyList}" HorizontalContentAlignment="Stretch" SelectionMode="Single">
<ListView.Resources>
<DataTemplate DataType="{x:Type properties:PasswordProperty}">
<ContentControl Content="{Binding}" Background="Red">
<ContentControl.Style>
<Style TargetType="{x:Type ContentControl}">
<Setter Property="ContentTemplate" Value="{StaticResource PasswordPropertyListViewItem}" />
<Style.Triggers>
<DataTrigger Binding="{Binding Path=DataContext.EditMode, RelativeSource= {RelativeSource FindAncestor, AncestorType={x:Type ListView}}}" Value="True">
<Setter Property="ContentTemplate" Value="{StaticResource EditPasswordPropertyListViewItem}" />
</DataTrigger>
</Style.Triggers>
</Style>
</ContentControl.Style>
</ContentControl>
</DataTemplate>
Example ListViewItem XAML that is referenced by DataTemplate:
<ListViewItem x:Class="PasswordPropertyListViewItem"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008">
<Border BorderThickness="0,0,0,1" BorderBrush="DarkGray">
<DockPanel LastChildFill="True" HorizontalAlignment="Stretch">
<Label Margin="8" Content="{Binding PropertyName}"></Label>
I expect that it does not matter where I click onto the ListViewItem but the item is selected in any case (Especially the red part of the image above).
Clemens provided a solution in his comment above.
I indeed nested two ListViewItems.
The solution is to change the type of my templated control to ContentControl.
<ContentControl x:Class="PasswordPropertyListViewItem"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008">
<Border BorderThickness="0,0,0,1" BorderBrush="DarkGray">
<DockPanel LastChildFill="True" HorizontalAlignment="Stretch">
<Label Margin="8" Content="{Binding PropertyName}"></Label>
Thanks Clemens!

Can't set both ContentTemplateSelector and Template properties on a DataGridColumnHeader

In short, the question title says it all. For those that want more detail, here is the crux of my problem: I need to apply a custom ControlTemplate to the DataGridColumnHeader elements in my DataGrid control, but I also need to style them differently, depending on the cell data nearest the header. However, when I set both the ContentTemplateSelector and Template properties on a DataGridColumnHeader element, the DataTemplateSelector that is set as the value of the ContentTemplateSelector property is not called. Commenting out the Template property setting confirms this to be the case, as the DataTemplateSelector element will now be called.
Yes, I know that you guys love to see some code, but I have completely templated the whole DataGrid control to look like Excel, so as you can imagine, I have far too much code to display here. But just to please you code hungry devs, I've recreated my problem in a much simpler example... let's first see the XAML:
<Window x:Class="WpfApp1.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:WpfApp1"
xmlns:System="clr-namespace:System;assembly=mscorlib"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid>
<DataGrid>
<DataGrid.Columns>
<DataGridTemplateColumn>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding}" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
<DataGrid.Items>
<System:String>One</System:String>
<System:String>Two</System:String>
<System:String>Three</System:String>
</DataGrid.Items>
<DataGrid.Resources>
<Local:StringDataTemplateSelector x:Key="StringDataTemplateSelector" />
<Style TargetType="{x:Type DataGridColumnHeader}" BasedOn="{StaticResource {x:Type DataGridColumnHeader}}">
<Setter Property="ContentTemplateSelector" Value="{StaticResource StringDataTemplateSelector}" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type DataGridColumnHeader}">
<Grid>
<Thumb x:Name="PART_LeftHeaderGripper" HorizontalAlignment="Left" />
<Thumb x:Name="PART_RightHeaderGripper" HorizontalAlignment="Right" />
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</DataGrid.Resources>
</DataGrid>
</Grid>
</Window>
Now the most simple DataTemplateSelector class:
using System.Diagnostics;
using System.Windows;
using System.Windows.Controls;
namespace WpfApp1
{
public class StringDataTemplateSelector : DataTemplateSelector
{
public override DataTemplate SelectTemplate(object item, DependencyObject container)
{
Debugger.Break();
return null;
}
}
}
In the XAML, we see a DataGrid, with just one DataGridTemplateColumn and three string values, one on each row, and some resources. There is a Style for the DataGridColumnHeader element in the Resource section, with the most simple ControlTemplate set up for it, that only includes the required named parts from the default ControlTemplate.
If you run the application as it is, then it will NOT currently break at the Debugger.Break() method in the StringDataTemplateSelector class. This is unexpected. If you now comment out the setting of the Template property in the Style and run the application again, then you will now see that program execution will now break at the Debugger.Break() method, as expected.
Further information:
In the Remarks section of the ContentControl.ContentTemplateSelector Property page of MSDN, it states that
If both the ContentTemplateSelector and the ContentTemplate properties are set, then this property is ignored.
However, it does not mention the Template property and there is also no mention of this on the Control.Template Property page on MSDN.
Furthermore, I tried this same setup using a simple Button control and can confirm that setting both the ContentTemplateSelector and the ContentTemplate properties on that does NOT stop the StringDataTemplateSelector class from being called:
<ItemsControl>
<ItemsControl.Resources>
<Local:StringDataTemplateSelector x:Key="StringDataTemplateSelector" />
<Style TargetType="{x:Type Button}">
<Setter Property="ContentTemplateSelector" Value="{StaticResource StringDataTemplateSelector}" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Grid>
<Ellipse Stroke="Red" StrokeThickness="1" Width="{TemplateBinding ActualWidth}" Height="{TemplateBinding Height}" />
<ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" />
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ItemsControl.Resources>
<Button Content="One" />
<Button Content="Two" />
<Button Content="Three" />
</ItemsControl>
So, what I'm after is a way to apply a custom ControlTemplate element to the DataGridColumnHeader objects, yet still be able to have the DataTemplateSelector class called during the rendering process.
add a content presenter in your controltemplate?
<ControlTemplate TargetType="{x:Type DataGridColumnHeader}">
<Grid>
<Thumb x:Name="PART_LeftHeaderGripper" HorizontalAlignment="Left" />
<Thumb x:Name="PART_RightHeaderGripper" HorizontalAlignment="Right" />
<ContentPresenter></ContentPresenter>
</Grid>
</ControlTemplate>

WPF: Simple MSWord-like color picker button

Is there a quick and easy way to implement a color picker button like the one in MS Word?
I want the user to choose from a number of predefined colors in a dropdown. The selected color should be displayed when the button is closed. When the user clicks the button, an event or command should be triggered. I want to use one button instance to set the text color in a RichTextBox, and another one to set the background color (similar to MS Word).
My first approach was to use a ComboBox with a DataTemplate which contains a button.
This does not work: The button's command is not triggered when the user clicks it. Instead, the dropdown of the ComboBox opens. I don't know the exact reason, but maybe the IsHitTestVisible=false attributes in the ComboBox default template? See: http://msdn.microsoft.com/en-us/library/dd334408%28v=vs.95%29.aspx
<UserControl x:Class="MyBrushPicker"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
Height="Auto" Width="Auto" MinWidth="50">
<UserControl.Resources>
<!--
Provide two different DataTemplates:
- SelectionBoxTemplate is used to display the selected color when the ComboBox is closed.
It contains a button which should be clickable (does not work).
- NormalItemTemplate is used to display a color in the opened ComboBox popup.
See:
http://stackoverflow.com/questions/2214696/wpf-how-to-customize-selectionboxitem-in-combobox
-->
<DataTemplate x:Key="NormalItemTemplate">
<Border Height="44" Width="44" Margin="3,3,3,3" BorderThickness="1" BorderBrush="Black" Background="{Binding Mode=OneWay}"/>
</DataTemplate>
<DataTemplate x:Key="SelectionBoxTemplate">
<!-- This button cannot be clicked: PreviewMouseDown and Button_Click events are never triggered. -->
<Button Click="Button_Click" PreviewMouseDown="Button_PreviewMouseDown">
<Border Height="44" Width="44" Margin="3,3,3,3" BorderThickness="1" BorderBrush="Black" Background="{Binding Mode=OneWay}"/>
</Button>
</DataTemplate>
<DataTemplate x:Key="CombinedTemplate">
<ContentPresenter x:Name="Presenter"
Content="{Binding}"
ContentTemplate="{StaticResource NormalItemTemplate}" />
<DataTemplate.Triggers>
<DataTrigger
Binding="{Binding RelativeSource={RelativeSource FindAncestor,ComboBoxItem,1}}"
Value="{x:Null}">
<Setter TargetName="Presenter" Property="ContentTemplate"
Value="{StaticResource SelectionBoxTemplate}" />
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
</UserControl.Resources>
<ComboBox IsReadOnly="True" IsEditable="False"
ItemsSource="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}}, Path=SelectableBrushes, Mode=OneWay}"
SelectedItem="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}}, Path=SelectedBrush, Mode=TwoWay}"
ScrollViewer.VerticalScrollBarVisibility="Auto"
MinHeight="50"
MaxDropDownHeight="200"
ItemTemplate="{StaticResource CombinedTemplate}"
>
<ComboBox.Resources>
<Style TargetType="ComboBox">
<Setter Property="ItemsPanel">
<Setter.Value>
<ItemsPanelTemplate>
<WrapPanel IsItemsHost="True" Orientation="Horizontal" Width="200" />
</ItemsPanelTemplate>
</Setter.Value>
</Setter>
</Style>
<Style TargetType="ComboBoxItem">
<Setter Property="Width" Value="50" />
<Setter Property="Height" Value="50" />
</Style>
</ComboBox.Resources>
</ComboBox>
</UserControl>
Is there a way to make the button work correctly?
Are there any better approaches?
EDIT: Using the Snoop tool revealed that the IsHitTestVisible attribute of the unnamed ContentPresenter inside the ComboBox is actually set to false (ValueSource: ParentTemplate). If I set this property to true using Snoop, the button becomes clickable.
Can I change this property from a style?
At least, the following doesn't work:
<ComboBox.Resources>
<Style TargetType="ContentPresenter">
<Setter Property="IsHitTestVisible" Value="True" />
</Style>
</ComboBox.Resources>
Assuming you are not just doing this as a learning exercise (which make using a library pointless)...
Take a look at: Extended WPF Toolkit - Color Picker
I've used it before for simple a plug-and-play WPF color-picker and it should solve your problem nicely.

Setting Button's Content to <Image> via Styles

Can't get this to work:
<UserControl>
<UserControl.Resources>
<ResourceDictionary>
<Style x:Key="TestStyle" TargetType="{x:Type Button}">
<Setter Property="Button.Content">
<Setter.Value>
<Image Source="D:\Temp\dictionary16.png"/>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
</UserControl.Resources>
<StackPanel VerticalAlignment="Top" HorizontalAlignment="Left">
<Button Style="{StaticResource TestStyle}"/>
<Button Style="{StaticResource TestStyle}"/>
</StackPanel>
</UserControl>
This code throws the following exception (pointing to the second button):
Specified element is already the logical child of another element. Disconnect it first.
The style creates one instance of the Image, you cannot use it in two places like this. You can create the image as a separate resource with x:Shared= false and reference it in the style then a new one will be created in every place the style is used.
e.g.
<UserControl>
<UserControl.Resources>
<Image x:Key="img" x:Shared="false" Source="D:\Temp\dictionary16.png" />
<Style x:Key="TestStyle" TargetType="{x:Type Button}">
<Setter Property="Content" Value="{StaticResource img}" />
</Style>
</UserControl.Resources>
<StackPanel VerticalAlignment="Top" HorizontalAlignment="Left">
<Button Style="{StaticResource TestStyle}" />
<Button Style="{StaticResource TestStyle}" />
</StackPanel>
</UserControl>
Already yesterday i found a user with a similar problem: WPF - Change a button's content in a style?
This post got me to this soloution (couldn't post it because of 8 hour limit of stackoverflow -.-)
<Setter Property="ContentTemplate">
<Setter.Value>
<DataTemplate>
<Image Source="{mcWPF:LangRes imgSettings16, Bitmap}" Height="14"/>
</DataTemplate>
</Setter.Value>
</Setter>
Don't know weather this is more clean/dirty/better than H.B.'s soloution

Why is this XAML invalid?

This XAML compiles and runs without any runtime errors:
<Window
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:Custom="http://schemas.microsoft.com/wpf/2008/toolkit" x:Class="WpfApplication1.Window1"
Title="Window1" Height="300" Width="300" mc:Ignorable="d">
<StackPanel Orientation="Vertical" d:LayoutOverrides="Height" DataContext="{Binding Source={StaticResource booksDataSource}}">
<Custom:DataGrid ItemsSource="{Binding Mode=Default, XPath=/catalog/book}" AutoGenerateColumns="False">
<Custom:DataGrid.Resources>
<ControlTemplate x:Key="TemplateLoverBirds">
<StackPanel Orientation="Horizontal">
<TextBlock Text="Great book!" />
<TextBlock x:Name="textBlock" Text="{Binding Mode=Default, XPath=title}" />
</StackPanel>
</ControlTemplate>
</Custom:DataGrid.Resources>
<Custom:DataGrid.Columns>
<Custom:DataGridTextColumn Binding="{Binding Mode=Default, XPath=author}"/>
<Custom:DataGridTemplateColumn>
<Custom:DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Control x:Name="TitleControl">
<Control.Template>
<ControlTemplate TargetType="{x:Type Control}">
<TextBlock Text="{Binding Mode=Default, XPath=title}" />
</ControlTemplate>
</Control.Template>
</Control>
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding XPath=title}" Value="Lover Birds">
<Setter TargetName="TitleControl" Property="Template" Value="{StaticResource TemplateLoverBirds}" />
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
</Custom:DataGridTemplateColumn.CellTemplate>
</Custom:DataGridTemplateColumn>
</Custom:DataGrid.Columns>
</Custom:DataGrid>
</StackPanel>
</Window>
But at design time in Blend this is marked as invalid XAML---and in Visual Studio design time the "Load Cancelled" screen shows (but loads properly after clicking Resume loading the designer).
Blend only supports a subset of WPF. I have noticed that EventSetters kill blend as well. I have the same problem as you. I have many windows which run fine, but cant be viewed in blend for odd reasons.
Strategy to diagnose Expression Blend 2 failure to open Window
I think maybe the Custom:DataGrid might not be supported. I dont know, just guessing. If your window instantiates and runs fine, then i guess blend is bugged.
Allright I fixed the issue like follows:
Change:
xmlns:Custom="http://schemas.microsoft.com/wpf/2008/toolkit
To:
xmlns:Custom="clr-namespace:Microsoft.Windows.Controls;assembly=WpfToolkit"
Make sure you have a good version of the WpfToolkit. Make a reference to the Toolkit and you can work with it.

Resources