Binding custom Dependency Property on User Control with ControlTemplate - c#

I've created a custom button with a ControlTemplate.
I used a ControlTemplate to make it possible to bind the default properties of UserControl, such as Background or Foreground.
But, if I add custom dependency properties (for example CornerRadius) I get two errors:
"The member 'CornerRadius' is not recognized or is not accessible."
"Cannot find the static member 'CornerRadiusProperty' on the type 'UserControl'."
Xaml:
<UserControl x:Class="MyProject.MyButton"
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"
d:DesignHeight="50" d:DesignWidth="50"
BorderThickness="1" BorderBrush="White" Background="Black"
Content="OK" Foreground="White">
<UserControl.Template>
<ControlTemplate TargetType="UserControl">
<Border Name="ground"
BorderThickness="{TemplateBinding BorderThickness}"
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}"
CornerRadius="{TemplateBinding CornerRadius}">
<Label Name="content"
VerticalContentAlignment="Center"
HorizontalContentAlignment="Center"
Content="{TemplateBinding Content}"
Foreground="{TemplateBinding Foreground}"
FontFamily="{TemplateBinding FontFamily}"
FontWeight="{TemplateBinding FontWeight}"
FontSize="{TemplateBinding FontSize}"/>
</Border>
</ControlTemplate>
</UserControl.Template>
</UserControl>
Code behind:
namespace MyProject
{
public partial class MyButton : UserControl
{
public static readonly DependencyProperty CornerRadiusProperty =
DependencyProperty.Register("CornerRadius", typeof(CornerRadius), typeof(MyButton));
public CornerRadius CornerRadius
{
get => (CornerRadius)GetValue(CornerRadiusProperty);
set => SetValue(CornerRadiusProperty, value);
}
public MyButton() => InitializeComponent();
}
}
If I use the solution specified here User control with custom properties I get this problem Wpf - Custom control: How to override default properties?.
So, there is a solution that avoid both problems?

A custom Button should not be a UserControl, but instead directly derive from Button.
Add a "Custom Control (WPF)" to you Visual Studio Project and modify it like this:
public class MyButton : Button
{
static MyButton()
{
DefaultStyleKeyProperty.OverrideMetadata(
typeof(MyButton),
new FrameworkPropertyMetadata(typeof(MyButton)));
}
public static readonly DependencyProperty CornerRadiusProperty =
DependencyProperty.Register(
nameof(CornerRadius), typeof(CornerRadius), typeof(MyButton));
public CornerRadius CornerRadius
{
get => (CornerRadius)GetValue(CornerRadiusProperty);
set => SetValue(CornerRadiusProperty, value);
}
}
Then change its default Style in the generated Themes\Generic.xaml file:
<Style TargetType="local:MyButton">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="local:MyButton">
<Border Name="ground"
BorderThickness="{TemplateBinding BorderThickness}"
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}"
CornerRadius="{TemplateBinding CornerRadius}">
<Label Name="content"
VerticalContentAlignment="Center"
HorizontalContentAlignment="Center"
Content="{TemplateBinding Content}"
Foreground="{TemplateBinding Foreground}"
FontFamily="{TemplateBinding FontFamily}"
FontWeight="{TemplateBinding FontWeight}"
FontSize="{TemplateBinding FontSize}"/>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
See Control Authoring Overview for details.

Related

Bind "Placement" property for PART_Popup component in dynamically creted menu (WPF)

Long story short. I have a dynamically created menu, viewModel for every item is below:
public class MenuItemViewModel
{
private readonly ICommand _command;
public MenuItemViewModel(Action<object> action)
{
_command = new CommandViewModel(action);
}
public string Header { get; set; }
public System.Windows.Controls.Primitives.PlacementMode Placement { get; set; }
public ObservableCollection<MenuItemViewModel> MenuItems { get; set; }
public ICommand Command
{
get
{
return _command;
}
}
}
Data context for whole window is another view model that has public ObservableCollection of those menuViewModel items"
public ObservableCollection<MenuItemViewModel> MenuItems { get; set; }
And after propgram startup I am adding new entries like this:
var currentDevice = (ControlableDeviceViewModel)sender;
var cmds = new ObservableCollection<MenuItemViewModel>();
foreach(var cmd in currentDevice.AvailableCommands)
{
cmds.Add(new MenuItemViewModel(cmd.Execute) { Header = cmd.CommandName,
Placement = System.Windows.Controls.Primitives.PlacementMode.Right});
}
MenuItems[0].MenuItems.Add(
new MenuItemViewModel((delegate {
RaiseAddNewDeviceEvent();
}))
{ Header = "Add new..." });
MenuItems[0].MenuItems.Add(
new MenuItemViewModel(null)
{
Header = currentDevice.Name + "->",
MenuItems = cmds
});
}
As you can see here I am adding placement only to cmds items because i want them to pop-up to right. Default behaviour is to pop up to bottom. And when i set Placement in my template in XAML it obviously set it for all items. But I want to set it only for specific item.
No matter in which way i try to bind for "Property" placement in model it is not working properly. It always have its default value "Bottom"
<Popup x:Name="PART_Popup" AllowsTransparency="true" Focusable="false" HorizontalOffset="2" IsOpen="{Binding IsSubmenuOpen, RelativeSource={RelativeSource TemplatedParent}}" PopupAnimation="{DynamicResource {x:Static SystemParameters.MenuPopupAnimationKey}}" Placement="{Binding RelativeSource={RelativeSource AncestorType={x:Type MenuItem},AncestorLevel='2'}, Path= Placement }" diag:PresentationTraceSources.TraceLevel="High" VerticalOffset="-1">
below is xaml part responsible for menu layout:
<Menu DockPanel.Dock="Top"
ItemsSource="{Binding MenuItems}"
Grid.Column="0"
Grid.ColumnSpan="5"
Grid.Row="0"
Foreground="White"
Background="Black"
xmlns:diag="clr-namespace:System.Diagnostics;assembly=WindowsBase"
>
<Menu.ItemContainerStyle>
<Style TargetType="{x:Type MenuItem}">
<Setter Property="Command" Value="{Binding Command}" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type MenuItem}">
<Grid SnapsToDevicePixels="true">
<DockPanel>
<ContentPresenter x:Name="Icon" ContentSource="Icon" Margin="4,0,6,0" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="Center"/>
<Path x:Name="GlyphPanel" Fill="{TemplateBinding Foreground}" FlowDirection="LeftToRight" Margin="7,0,0,0" Visibility="Collapsed" VerticalAlignment="Center"/>
<ContentPresenter x:Name="content" ContentSource="Header" Margin="{TemplateBinding Padding}" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
</DockPanel>
<Popup x:Name="PART_Popup" AllowsTransparency="true" Focusable="false" HorizontalOffset="2" IsOpen="{Binding IsSubmenuOpen, RelativeSource={RelativeSource TemplatedParent}}" PopupAnimation="{DynamicResource {x:Static SystemParameters.MenuPopupAnimationKey}}" Placement="{Binding RelativeSource={RelativeSource AncestorType={x:Type MenuItem},AncestorLevel='1'}, Path= Placement }" diag:PresentationTraceSources.TraceLevel="High" VerticalOffset="-1">
<Border BorderThickness="2" BorderBrush="Black" Background="Black">
<ScrollViewer x:Name="SubMenuScrollViewer" CanContentScroll="true" Style="{DynamicResource {ComponentResourceKey ResourceId=MenuScrollViewer, TypeInTargetAssembly={x:Type FrameworkElement}}}">
<Grid RenderOptions.ClearTypeHint="Enabled">
<ItemsPresenter x:Name="ItemsPresenter" KeyboardNavigation.DirectionalNavigation="Cycle" Grid.IsSharedSizeScope="true" Margin="-1" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" KeyboardNavigation.TabNavigation="Cycle"/>
</Grid>
</ScrollViewer>
</Border>
</Popup>
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="TextBlock.Foreground" Value="Gray" TargetName="content"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Menu.ItemContainerStyle>
<Menu.ItemTemplate>
<HierarchicalDataTemplate DataType="{x:Type viewModels:MenuItemViewModel}" ItemsSource="{Binding Path=MenuItems}">
<TextBlock Text="{Binding Header}"
Padding="3"/>
</HierarchicalDataTemplate>
</Menu.ItemTemplate>
</Menu>
Many thanks for help me with solving this issue
Looks like the viewModel does not implement INotifyPropertyChanged interface and that's why the placement is always default.
Try this
public class MenuItemViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
private readonly ICommand _command;
public MenuItemViewModel(Action<object> action)
{
_command = new CommandViewModel(action);
}
private string header;
public string Header
{
get
{
return header;
}
set
{
header = value;
NotifyPropertyChanged();
}
}
private System.Windows.Controls.Primitives.PlacementMode placement;
public System.Windows.Controls.Primitives.PlacementMode Placement
{
get
{
return placement;
}
set
{
placement = value;
NotifyPropertyChanged();
}
}
public ObservableCollection<MenuItemViewModel> MenuItems { get; set; }
public ICommand Command
{
get
{
return _command;
}
}
}

Parse XAML styles in code behind and load custom control

I have a c++ program that parse C# codes using Roslyn.
I need to convert my styles and custom controls to just "code-behind".
for example I have a simple custom control contains a button .
XAML Style :
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:CUSTOM_LIBRARY_PARSE">
<Style TargetType="{x:Type local:CustomControl1}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:CustomControl1}">
<Border Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
<Button Background="#FF487DF0" >
<Label VerticalContentAlignment="Center" HorizontalContentAlignment="Center" OpacityMask="#FFC3C3C3" Content="{Binding text_of_button_Value, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:CustomControl1}}}" />
</Button>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
Code-Behind of Control :
using System;
using System.Windows;
using System.Windows.Controls;
namespace CUSTOM_LIBRARY_PARSE
{
public class CustomControl1 : Control
{
public static readonly DependencyProperty text_of_button
= DependencyProperty.Register(
"text_of_button_Value",
typeof(string),
typeof(CustomControl1),
new PropertyMetadata(Environment.UserName)
);
public string text_of_button_Value
{
get { return (string)GetValue(text_of_button); }
set { SetValue(text_of_button, value); }
}
static CustomControl1()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(CustomControl1), new FrameworkPropertyMetadata(typeof(CustomControl1)));
}
}
}
Now , I need to know how to embed xaml code in code behind as a string like :
string code_xaml = "<ResourceDictionary\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n xmlns:local=\"clr-namespace:CUSTOM_LIBRARY_PARSE\">\n <Style TargetType=\"{x:Type local:CustomControl1}\">\n <Setter Property=\"Template\">\n <Setter.Value>\n <ControlTemplate TargetType=\"{x:Type local:CustomControl1}\">\n <Border Background=\"{TemplateBinding Background}\"\n BorderBrush=\"{TemplateBinding BorderBrush}\"\n BorderThickness=\"{TemplateBinding BorderThickness}\">\n <Button Background=\"#FF487DF0\" >\n <Label VerticalContentAlignment=\"Center\" HorizontalContentAlignment=\"Center\" OpacityMask=\"#FFC3C3C3\" Content=\"{Binding text_of_button_Value, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:CustomControl1}}}\" />\n </Button>\n </Border>\n </ControlTemplate>\n </Setter.Value>\n </Setter>\n </Style>\n</ResourceDictionary>\n";
And next parse it with XamlParser and load it to customcontrol1
is that possible ?
thanks
The Answer is :
Create a public version of custom control :
public CustomControl1()
{
}
Create a public version of custom control :
public CustomControl1()
{
ResourceDictionary Parse_Resource = XamlReader.Parse(code_xaml) as ResourceDictionary;
this.Resources = Parse_Resource;
}
Solved :D

how to Detect selected item in ContentControl in wpf

I'm trying to develop a HamburgerMenu. a ContentControl that i restyled it.
my xaml code is something like this :
<Style TargetType="local:HamburgerMenu">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="local:HamburgerMenu">
<Grid x:Name="mainGrid" Background="{TemplateBinding Background}">
<!--HamburgerMenu button-->
<Border x:Name="border" Background="{TemplateBinding Background}" HorizontalAlignment="Left" VerticalAlignment="Top" Height="40" Width="50">
<ToggleButton x:Name="menuIcon" Background="Red" HorizontalAlignment="Left" VerticalAlignment="Top" Height="40" Width="50" IsChecked="{Binding RelativeSource={RelativeSource AncestorType={x:Type local:HamburgerMenu}}, Path=IsOpen}">
<Path x:Name="path" HorizontalAlignment="Center" VerticalAlignment="Center" Stretch="Uniform" Width="30" Fill="{TemplateBinding MenuIconColor}" Data="M2,15.5L22,15.5 22,17.5 2,17.5 2,15.5z M2,10.5L22,10.5 22,12.5 2,12.5 2,10.5z M2,5.5L22,5.5 22,7.5 2,7.5 2,5.5z"/>
</ToggleButton>
</Border>
<!-- HamburgerMenu Items List-->
<ListBox x:Name="listbox" ItemsSource="{TemplateBinding Content}" HorizontalAlignment="Left" Margin="0,40,0,0" VerticalAlignment="Top" ScrollViewer.HorizontalScrollBarVisibility="Disabled" SelectedIndex="0"/>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style TargetType="local:HamburgerMenuItem">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="local:HamburgerMenuItem">
<Button x:Name="ListBoxItemButton" Command="{TemplateBinding SelectionCommand}" HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch">
<Grid x:Name="MainGrid">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="5" />
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Grid Grid.ColumnSpan="2">
<Grid Background="Transparent" Margin="0" Width="300">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="45" />
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Grid Grid.Column="1">
<TextBlock Text="{TemplateBinding Text}" Margin="10,0,0,0" HorizontalAlignment="Left" VerticalAlignment="Center" FontFamily="Segoe UI Light" FontSize="18" Foreground="{TemplateBinding Foreground}" TextWrapping="Wrap"/>
</Grid>
<Grid Grid.Column="0">
<Image Source="{TemplateBinding Icon}" Margin="10,5,5,5"/>
</Grid>
</Grid>
</Grid>
<Grid Name="ItemSelectedIndicator" Grid.Column="0" Background="{TemplateBinding SelectionIndicatorColor}" Visibility="Collapsed" />
</Grid>
</Button>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
and this is my HamburgerMenu classes :
public class HamburgerMenu : ContentControl
{
public new List<HamburgerMenuItem> Content
{
get { return (List<HamburgerMenuItem>)GetValue(ContentProperty); }
set { SetValue(ContentProperty, value); }
}
public new static readonly DependencyProperty ContentProperty =
DependencyProperty.Register("Content", typeof(List<HamburgerMenuItem>), typeof(HamburgerMenu),
new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.AffectsRender | FrameworkPropertyMetadataOptions.AffectsMeasure));
static HamburgerMenu()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(HamburgerMenu), new FrameworkPropertyMetadata(typeof(HamburgerMenu)));
}
public override void BeginInit()
{
Content = new List<HamburgerMenuItem>();
base.BeginInit();
}
}
public class HamburgerMenuItem : ListBoxItem
{
static HamburgerMenuItem()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(HamburgerMenuItem), new FrameworkPropertyMetadata(typeof(HamburgerMenuItem)));
}
public string Text
{
get { return (string)GetValue(TextProperty); }
set { SetValue(TextProperty, value); }
}
public static readonly DependencyProperty TextProperty =
DependencyProperty.Register("Text", typeof(string), typeof(HamburgerMenuItem), new PropertyMetadata(String.Empty));
}
my question is how i can find witch ListBox item is selected in my window where i used my custom Control.
You could add a "SelectedItem" dependency property to your custom control and bind the SelectedItem property of the ListBox in the ControlTemplate to this one:
<!-- HamburgerMenu Items List-->
<ListBox x:Name="listbox" ItemsSource="{TemplateBinding Content}"
SelectedItem="{Binding SelectedItem, RelativeSource={RelativeSource TemplatedParent}}"
HorizontalAlignment="Left" Margin="0,40,0,0" VerticalAlignment="Top" ScrollViewer.HorizontalScrollBarVisibility="Disabled" SelectedIndex="0"/>
You then bind your new dependency property to the source property in your window:
<local:HamburgerMenuItem ... SelectedItem="{Binding YourSourceProperty}" />

Modify TextBox value when Button was clicked in custom control library

I create one textbox and button in custom control library, the initial text box value is "Welcome" when the button was clicked the textbox text value is modified to "Hi".
Generic.Xaml:
<ResourceDictionary
x:Class="WpfCustomControlLibrary2.Themes.Class1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfCustomControlLibrary2">
<Style TargetType="{x:Type local:CustomControl1}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:CustomControl1}">
<Border Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
<WrapPanel HorizontalAlignment="Center" VerticalAlignment="Center">
<TextBox x:Name="txb" Text="Welcome" Width="50" Height="30" FontSize="15"/>
<Button Content="+" Width="35" Height="30" FontSize="15" Click="Button_Click_Add" />
</WrapPanel>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
Class1.cs:
namespace WpfCustomControlLibrary2.Themes
{
partial class Class1
{
private void Button_Click_Add(object sender, RoutedEventArgs e)
{
//What i do here
}
}
}
MainWindow.Xaml
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfCustomControlLibrary2;assembly=WpfCustomControlLibrary2"
Title="MainWindow" Height="350" Width="525">
<Grid x:Name="grid">
<local:CustomControl1 />
</Grid>
</Window>
Please help to solve this problem, Thanks
You can`t do it, like you do it.
And you must follow name rules also.
Try it:
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfCustomControlLibrary2;assembly=WpfCustomControlLibrary2">
<Style TargetType="{x:Type local:CustomControl1}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:CustomControl1}">
<Border Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
<WrapPanel HorizontalAlignment="Center" VerticalAlignment="Center">
<TextBox x:Name="PART_TextBox" Text="Welcome"/>
<Button x:Name="PART_Button" Content="+" />
</WrapPanel>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
and
[TemplatePart(Name = "PART_TextBox", Type = typeof(TextBox))]
[TemplatePart(Name = "PART_Button", Type = typeof(Button))]
public class CustomControl1 : Control
{
static CustomControl1()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(CustomControl1), new FrameworkPropertyMetadata(typeof(CustomControl1)));
}
public CustomControl1()
{
}
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
var button = GetTemplateChild("PART_Button") as Button;
if (button != null)
{
button.Click += Button_Click;
}
}
private void Button_Click(object sender, RoutedEventArgs e)
{
var textBox = GetTemplateChild("PART_TextBox") as TextBox;
if (textBox != null)
{
textBox.Text = "HI!";
}
}
}

wp7 TemplateBinding Content not working

I am new in working with wpf and currently I am trying to do the following: I have created a simple ContenctControl (CtrpushPinContent) that contains a TextBlock:
<ContentControl x:Class="CtrpushPinContent" ...
<Grid x:Name="LayoutRoot" Background="{x:Null}">
<Border BorderThickness="3" Name="border1" CornerRadius="15" BorderBrush="#FF070707" Margin="0,0,0,0">
<Border BorderBrush="Silver" BorderThickness="3" Name="border2" CornerRadius="15" Background="#FF413E3E">
<TextBlock Name="textBlock1" TextAlignment="Center" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="4" Foreground="White" />
</Border>
</Border>
</Grid>
</ContentControl>
The cs file looks like this:
public partial class CtrpushPinContent : ContentControl
{
public static readonly DependencyProperty CaptionProperty =
DependencyProperty.Register("Text",
typeof(string),
typeof(CtrpushPinContent),
new PropertyMetadata(string.Empty));
public string Text
{
get { return textBlock1.Text; }
set { textBlock1.Text = value; }
}
public CtrpushPinContent()
{
InitializeComponent();
}
}
On the main PhoneApplicationPage I try to do the following:
<phone:PhoneApplicationPage.Resources>
<Style TargetType="my:Pushpin" x:Key="PushpinStyle">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="my:Pushpin">
<Grid x:Name="ContentGrid">
<StackPanel Orientation="Vertical">
<Grid Background="{x:Null}" HorizontalAlignment="Right" MinHeight="31" MinWidth="29">
<LJTileSources:CtrpushPinContent HorizontalAlignment="Right" Text="{TemplateBinding Content}" Margin="4" ContentTemplate="{TemplateBinding ContentTemplate}" />
</Grid>
<Image Source="/WifiHotSpot;component/Images/blackPinNoShadow.png" Width="54" Height="54" HorizontalAlignment="Center"></Image>
</StackPanel>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</phone:PhoneApplicationPage.Resources>
<Grid>
<my:Map Margin="0,1,0,0" Name="map1" LogoVisibility="Collapsed" Height="576" CredentialsProvider="key" ZoomLevel="2">
<my:Pushpin Style="{StaticResource PushpinStyle}" Content="Test" Location="50.0863762,14.42814" PositionOrigin="BottomLeft"></my:Pushpin>
</my:Map>
</Grid>
However my solution is not working. I cannot see any effect of the
<my:Pushpin Style="{StaticResource PushpinStyle}" Content="Test" .../>
I believe the problem is somewhere in the style declaration:
<LJTileSources:CtrpushPinContent HorizontalAlignment="Right" Text="{TemplateBinding Content}" Margin="4" ContentTemplate="{TemplateBinding ContentTemplate}" />
because when I change it to
<LJTileSources:CtrpushPinContent HorizontalAlignment="Right" Text="TestText" Margin="4" ContentTemplate="{TemplateBinding ContentTemplate}" />
it displays the "TestText" as required.
In your case for solve this problem quickly you need to implement this:
public static readonly DependencyProperty CaptionProperty =
DependencyProperty.Register("Text",
typeof(string),
typeof(CtrpushPinContent),
new PropertyMetadata(string.Empty, OnTextChanged));
public string Text
{
get { return textBlock1.Text; }
set { textBlock1.Text = value; }
}
private static void OnTextChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
((CtrpushPinContent)sender).textBlock1.Text = (string)e.NewValue;
}
public CtrpushPinContent()
{
InitializeComponent();
}
When you set text in Pushpin template:
<LJTileSources:CtrpushPinContent HorizontalAlignment="Right" Text="{TemplateBinding Content}"
Margin="4" ContentTemplate="{TemplateBinding ContentTemplate}" />
you don't set Text property in your control, you set value of dependency property CaptionProperty, because you registered it with name "Text". So when you set Text from xaml, you set exactly Caption property, not Text property of your control. So you need to create event of changing this dependency property for updating text in textBox1.

Categories