Is it actually possible to use bindings with the Setters Value property in VisualState, because when I try to use x:Bind the initial view of the page is not using the bindings and with Binding the page does not use them ever or do I need to do something additional?
For example if I use the layout below and I start the app with a width between 400 - 800 the PassInput Passwordbox will not have a placeholder. When I resize the window to more than 800 and then back it will finally have the placeholder.
Example:
<Page
x:Class="UWP.Learning.MainPage"
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"
x:Name="Page">
<RelativePanel Background="White">
<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="WindowSizeStates">
<VisualState x:Name="SmallState">
<VisualState.StateTriggers>
<AdaptiveTrigger MinWindowWidth="400" />
</VisualState.StateTriggers>
<VisualState.Setters>
<Setter Target="PassInput.PlaceholderText" Value="{x:Bind MyPlaceHolder, Mode=OneWay}" />
</VisualState.Setters>
</VisualState>
<VisualState x:Name="WideState">
<VisualState.StateTriggers>
<AdaptiveTrigger MinWindowWidth="800" />
</VisualState.StateTriggers>
<VisualState.Setters>
<Setter Target="PassInput.PlaceholderText" Value="{x:Null}" />
</VisualState.Setters>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
<TextBlock
Name="PassLabel"
RelativePanel.AlignTopWithPanel="True"
RelativePanel.AlignLeftWithPanel="True"
RelativePanel.AlignRightWithPanel="True"
Text="Pass input label"
HorizontalAlignment="Center" />
<PasswordBox
Name="PassInput"
RelativePanel.AlignLeftWithPanel="True"
RelativePanel.AlignRightWithPanel="True"
RelativePanel.Below="PassLabel"
VerticalAlignment="Center"
Margin="20,0" />
</RelativePanel>
</Page>
Code behind:
namespace UWP.Learning
{
using Windows.UI.Xaml.Controls;
public sealed partial class MainPage : Page
{
public MainPage() { this.InitializeComponent(); }
public string MyPlaceHolder => "FOOBAR";
}
}
Looks like a bug to me. An easy workaround is to have a one-time check within the Loaded event.
Loaded += (s, e) =>
{
switch (ActualWidth)
{
case var w when (w >= 400 && w < 800):
VisualStateManager.GoToState(this, "SmallState", false);
break;
case var w when (w >= 800):
VisualStateManager.GoToState(this, "WideState", false);
break;
}
};
Related
I have a very simple ListView whose ItemsSource is a ObservableCollection. Better show it with code:
MainPage.xaml:
<Page
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:Windows.UI.Xaml.Shapes"
x:Class="Test.MainPage" Background="Black" >
<Grid x:Name="Board" Background="Transparent" >
<ListView ItemsSource="{x:Bind LineList}">
<ListView.ItemTemplate>
<DataTemplate x:DataType="local:Line">
<StackPanel Orientation="Horizontal" Spacing="5">
<TextBlock Foreground="White" Text="{x:Bind Name}"/>
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Grid>
Mainpage.xaml.cs:
public sealed partial class MainPage : Page
{
public ObservableCollection<Line> LineList = new ObservableCollection<Line>();
public MainPage()
{
InitializeComponent();
LineList.CollectionChanged += List_CollectionChanged;
LineList.Add(new Line { Name = "Line1" });
LineList.Add(new Line { Name = "Line2" });
}
private void List_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if(e.Action == NotifyCollectionChangedAction.Add)
{
Board.Children.Add(e.NewItems[0] as Line);//if I comment out this line, no exception
}
}
}
What I actually want is that, when I add a Line on the ListView to show it's Name, it be also added in the Grid as an actual Shape. Note that, I am using the ListView only to show the Names of those Lines, and in the Grid I want an actual Line Shape
I don't know what I've done wrong, but the above attempt gives the stated Exception.
If these informations help:
No Exception occurs if I don't add the Line in the Grid
No Exception if : Board.Children.Add(new Line { Name = "Line2" });
I've been fiddling around with your code and I was able to track down what is wrong with your code. However I'm not really sure why it's happening.
The reason why you're getting errors is because you're trying to use same instance of an UIElement (i.e. Line) that you're binding to your ListView.ItemsSource. Why it's failing, is a bit of mystery to me. I suspect that it's forbidden to Bind and add the same UIElement to XAML, as it might create binding loops!? That's just a wild guess though. Anyways...
You shouldn't be using UIElement as the binding context - I can't think of any scenario that you would do such thing. You will be better off by creating a separate model, as per my previous answer (e.g. LineViewModel), and using that as your BindingContext. Your MainPage.xaml.cs code could look like this:
public sealed partial class MainPage : Page
{
public ObservableCollection<LineViewModel> Lines = new ObservableCollection<LineViewModel>();
public MainPage()
{
InitializeComponent();
Lines.CollectionChanged += LinesOnCollectionChanged;
Lines.Add(new LineViewModel { Name = "Line1" });
Lines.Add(new LineViewModel { Name = "Line2" });
}
private void LinesOnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.Action == NotifyCollectionChangedAction.Add)
{
MainGrid.Children.Add(new Line()
{
Name = (e.NewItems[0] as LineViewModel)?.Name ?? string.Empty,
Stroke = new SolidColorBrush(Colors.Black),
StrokeThickness = 12,
X1 = 0,
X2 = 10000
});
}
}
}
public class LineViewModel
{
public string Name { get; set; }
}
The MainPage.xaml will stay the same, as per my previous answer
I'm not sure if this is what you're after but here it goes
MainPage.xaml
<Page x:Class="App4.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:App4"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Page.Resources>
<Style x:Key="LineViewItemContainerStyle"
TargetType="ListViewItem">
<Setter Property="FontFamily"
Value="{ThemeResource ContentControlThemeFontFamily}" />
<Setter Property="FontSize"
Value="{ThemeResource ControlContentThemeFontSize}" />
<Setter Property="Background"
Value="{ThemeResource ListViewItemBackground}" />
<Setter Property="Foreground"
Value="{ThemeResource ListViewItemForeground}" />
<Setter Property="TabNavigation"
Value="Local" />
<Setter Property="IsHoldingEnabled"
Value="True" />
<Setter Property="Padding"
Value="0" />
<Setter Property="HorizontalContentAlignment"
Value="Stretch" />
<Setter Property="VerticalContentAlignment"
Value="Stretch" />
<Setter Property="MinWidth"
Value="{ThemeResource ListViewItemMinWidth}" />
<Setter Property="MinHeight"
Value="{ThemeResource ListViewItemMinHeight}" />
<Setter Property="AllowDrop"
Value="False" />
<Setter Property="UseSystemFocusVisuals"
Value="True" />
<Setter Property="FocusVisualMargin"
Value="0" />
<Setter Property="FocusVisualPrimaryBrush"
Value="{ThemeResource ListViewItemFocusVisualPrimaryBrush}" />
<Setter Property="FocusVisualPrimaryThickness"
Value="2" />
<Setter Property="FocusVisualSecondaryBrush"
Value="{ThemeResource ListViewItemFocusVisualSecondaryBrush}" />
<Setter Property="FocusVisualSecondaryThickness"
Value="1" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListViewItem">
<ListViewItemPresenter x:Name="Root"
CheckBrush="{ThemeResource ListViewItemCheckBrush}"
ContentMargin="{TemplateBinding Padding}"
CheckBoxBrush="{ThemeResource ListViewItemCheckBoxBrush}"
ContentTransitions="{TemplateBinding ContentTransitions}"
CheckMode="{ThemeResource ListViewItemCheckMode}"
DragOpacity="{ThemeResource ListViewItemDragThemeOpacity}"
DisabledOpacity="{ThemeResource ListViewItemDisabledThemeOpacity}"
DragBackground="{ThemeResource ListViewItemDragBackground}"
DragForeground="{ThemeResource ListViewItemDragForeground}"
FocusVisualSecondaryBrush="{TemplateBinding FocusVisualSecondaryBrush}"
FocusVisualPrimaryThickness="{TemplateBinding FocusVisualPrimaryThickness}"
FocusVisualSecondaryThickness="{TemplateBinding FocusVisualSecondaryThickness}"
FocusBorderBrush="{ThemeResource ListViewItemFocusBorderBrush}"
FocusVisualMargin="{TemplateBinding FocusVisualMargin}"
FocusVisualPrimaryBrush="{TemplateBinding FocusVisualPrimaryBrush}"
FocusSecondaryBorderBrush="{ThemeResource ListViewItemFocusSecondaryBorderBrush}"
HorizontalContentAlignment="{TemplateBinding HorizontalContentAlignment}"
Control.IsTemplateFocusTarget="True"
PressedBackground="{ThemeResource ListViewItemBackgroundPressed}"
PlaceholderBackground="{ThemeResource ListViewItemPlaceholderBackground}"
PointerOverForeground="{ThemeResource ListViewItemForegroundPointerOver}"
PointerOverBackground="{ThemeResource ListViewItemBackgroundPointerOver}"
ReorderHintOffset="{ThemeResource ListViewItemReorderHintThemeOffset}"
SelectedForeground="{ThemeResource ListViewItemForegroundSelected}"
SelectionCheckMarkVisualEnabled="{ThemeResource ListViewItemSelectionCheckMarkVisualEnabled}"
SelectedBackground="{ThemeResource ListViewItemBackgroundSelected}"
SelectedPressedBackground="{ThemeResource ListViewItemBackgroundSelectedPressed}"
SelectedPointerOverBackground="{ThemeResource ListViewItemBackgroundSelectedPointerOver}"
VerticalContentAlignment="{TemplateBinding VerticalContentAlignment}">
<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="CommonStates">
<VisualState x:Name="Normal" />
<VisualState x:Name="Selected" />
<VisualState x:Name="PointerOver">
<VisualState.Setters>
<Setter Target="Root.(RevealBrush.State)"
Value="PointerOver" />
</VisualState.Setters>
</VisualState>
<VisualState x:Name="PointerOverSelected">
<VisualState.Setters>
<Setter Target="Root.(RevealBrush.State)"
Value="PointerOver" />
</VisualState.Setters>
</VisualState>
<VisualState x:Name="PointerOverPressed">
<VisualState.Setters>
<Setter Target="Root.(RevealBrush.State)"
Value="Pressed" />
</VisualState.Setters>
</VisualState>
<VisualState x:Name="Pressed">
<VisualState.Setters>
<Setter Target="Root.(RevealBrush.State)"
Value="Pressed" />
</VisualState.Setters>
</VisualState>
<VisualState x:Name="PressedSelected">
<VisualState.Setters>
<Setter Target="Root.(RevealBrush.State)"
Value="Pressed" />
</VisualState.Setters>
</VisualState>
</VisualStateGroup>
<VisualStateGroup x:Name="DisabledStates">
<VisualState x:Name="Enabled" />
<VisualState x:Name="Disabled">
<VisualState.Setters>
<Setter Target="Root.RevealBorderThickness"
Value="0" />
</VisualState.Setters>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
</ListViewItemPresenter>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Page.Resources>
<Grid Background="Transparent">
<ListView ItemContainerStyle="{StaticResource LineViewItemContainerStyle}"
ItemsSource="{x:Bind Lines, Mode=OneTime}"
HorizontalContentAlignment="Stretch"
VerticalContentAlignment="Stretch">
<ListView.ItemTemplate>
<DataTemplate x:DataType="local:LineViewModel">
<Grid x:Name="ItemGrid">
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<TextBlock Foreground="Black"
Text="{x:Bind Name, Mode=OneWay}" />
<Border Grid.Row="1"
BorderBrush="Black"
BorderThickness="1" />
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Grid>
</Page>
MainPage.xaml.cs
public sealed partial class MainPage : Page
{
public ObservableCollection<LineViewModel> Lines = new ObservableCollection<LineViewModel>();
public MainPage()
{
InitializeComponent();
Lines.Add(new LineViewModel { Name = "Line1" });
Lines.Add(new LineViewModel { Name = "Line2" });
}
}
public class LineViewModel
{
public string Name { get; set; }
}
Note, that instead of using Line I used Border. Also, I needed to override base ListViewItemContainerStyle to set HorizontalContentAlignment and VerticalContentAlignment to Stretch, so that the DataTemplate elements can take up the entire space of the item
The result:
Simply i want to change the Grid's background color (in Silverlight) when the mouse enters and reset it when the mouse leaves.
So I tried different ways but no success. Here is what I have tried:
1: using EventTriggers:
<Grid.Triggers>
<EventTrigger RoutedEvent="MouseEnter">
<BeginStoryboard Storyboard="{StaticResouce mouseEnter}"/>
</EventTrigger>
</Grid.Triggers>
this doesn't work and say:
The member "IsMouseOver" is not recognized or is not accessible
2. using Style.Triggers
I tried setting some simple triggers in an Style with TargetType="Grid" but in Silverlight it seems there is no way to make Style.Triggers in XAML. Here is the code:
<Grid.Style>
<Style TargetType="Grid">
<Style.Triggers>
</Style.Triggers>
</Style>
</Grid.Style>
But it says:
The attachable property 'Triggers' was not found in type 'Style'.
3. using interaction libraries
I also used Interactivity.dll and interaction.dll but they didnt' work too.
Can anyone help how to change the grid background when the mouse enters in Silverlight?
There are three possible solutions:
First solution: Using VisualSates: Changing a Background on MouseOver in Silverlight can be done via VisualStates.
Here is an example:
<UserControl class="MyUserControlWithVisualStates">
<Grid x:Name="RootGrid" Background="UglyRed">
<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="CommonStates">
<VisualState x:Name="Normal"/>
<VisualState x:Name="Disabled"/>
<VisualState x:Name="MouseOver">
<Storyboard>
<ColorAnimation To="Green"
Storyboard.TargetProperty="(Background).(SolidColorBrush.Color)"
Storyboard.TargetName="RootGrid"/>
</Storyboard>
</VisualState>
</VisualStateGroup>
<VisualStateGroup x:Name="FocusStates">
<VisualState x:Name="Focused"/>
<VisualState x:Name="Unfocused"/>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
<OtherGridContent ... />
</Grid>
</UserControl>
and code behind:
public partial class MyUserControlWithVisualStates : UserControl
{
private bool m_isMouseOver;
public MyUserControlWithVisualStates()
{
InitializeComponent();
RootGrid.MouseEnter += OnRootGridMouseEnter;
RootGrid.MouseLeave += OnRootGridMouseLeave;
}
private void UpdateVisualStates()
{
if ( m_isMouseOver )
VisualStateManager.GoToState( this, "MouseOver", true );
else
VisualStateManager.GoToState( this, "Normal", true );
}
private void OnRootGridMouseLeave( object sender, MouseEventArgs e )
{
m_isMouseOver = false;
UpdateVisualStates();
}
private void OnRootGridMouseEnter( object sender, MouseEventArgs e )
{
m_isMouseOver = true;
UpdateVisualStates();
}
}
Second solution: Changing properties via codebehind: The MouseEnter and MouseLeave event handlers can just change the grid's background color.
public partial class MyUserControl : UserControl
{
private bool m_isMouseOver;
public MyUserControl()
{
InitializeComponent();
RootGrid.MouseEnter += OnRootGridMouseEnter;
RootGrid.MouseLeave += OnRootGridMouseLeave;
}
private void UpdateBackground()
{
if (m_isMouseOver)
((SolidColorBrush) RootGrid.Background).Color = Colors.Red;
else
((SolidColorBrush) RootGrid.Background).Color = Colors.Green;
}
private void OnRootGridMouseLeave( object sender, MouseEventArgs e )
{
m_isMouseOver = false;
UpdateBackground();
}
private void OnRootGridMouseEnter( object sender, MouseEventArgs e )
{
m_isMouseOver = true;
UpdateBackground();
}
}
Third solution: Using triggers and actions in xaml:
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions"
<Grid x:Name="TheGrid" Background="Blue">
<Grid.Resources>
<SolidColorBrush x:Key="MouseOverBrush" Color="Green"/>
<SolidColorBrush x:Key="NormalBrush" Color="Red"/>
</Grid.Resources>
<i:Interaction.Triggers>
<i:EventTrigger EventName="MouseEnter" SourceName="TheGrid">
<ei:ChangePropertyAction
TargetName="TheGrid"
PropertyName="Background"
Value="{StaticResource MouseOverBrush}"/>
</i:EventTrigger>
<i:EventTrigger EventName="MouseLeave" SourceName="TheGrid">
<ei:ChangePropertyAction
TargetName="TheGrid"
PropertyName="Background"
Value="{StaticResource NormalBrush}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</Grid>
I'm stuck trying to add a dependency property to a button. I have several buttons located in my header view and clicking on them changes the content in the ContentControl between different views. All this works great. I want the button that was clicked have a different forecolor than the others and it looks like I need to add a dependency property. I think I have all the pieces in place but can't figure out how to get them all to work together.
I have a string property named ViewState in my viewmodel which changes based upon the button being clicked. The property is changing and I'm calling RaisePropertyChanged when it happens. What do I need to do to bind the additional dependency property? I'm transitioning from the WinForm world and trying to mentally piece it all together but struggling a bit.
Here's what I have so far:
<Style TargetType="{x:Type Button}" x:Key="LocalButtonTemplate">
<Setter Property="Foreground" Value="White" />
<Setter Property="Background" Value="{x:Null}" />
<Setter Property="FontFamily" Value="Segoe UI" />
<Setter Property="FontSize" Value="18" />
<Setter Property="Cursor" Value="Hand" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Border x:Name="outerBorder" Background="{TemplateBinding Background}" Margin="4">
<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="ViewState">
<VisualState x:Name="Dashboard">
<Storyboard>
<ColorAnimation Duration="0:0:0.1" To="Yellow"
Storyboard.TargetProperty="(TextElement.Foreground).(SolidColorBrush.Color)"
Storyboard.TargetName="contentPresenter"/>
</Storyboard>
</VisualState>
<VisualState x:Name="AccountTables">
<Storyboard>
<ColorAnimation Duration="0:0:0.1" To="Red"
Storyboard.TargetProperty="(TextElement.Foreground).(SolidColorBrush.Color)"
Storyboard.TargetName="contentPresenter"/>
</Storyboard>
</VisualState>
<VisualState x:Name="Normal">
<Storyboard>
<ColorAnimation Duration="0:0:0.1" To="Purple"
Storyboard.TargetProperty="(TextElement.Foreground).(SolidColorBrush.Color)"
Storyboard.TargetName="contentPresenter"/>
</Storyboard>
</VisualState>
<VisualState x:Name="MouseOver">
<Storyboard>
<ColorAnimation Duration="0:0:0.1" To="#35A84D"
Storyboard.TargetProperty="(TextElement.Foreground).(SolidColorBrush.Color)"
Storyboard.TargetName="contentPresenter"/>
</Storyboard>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
<Grid>
<Border x:Name="Background" BorderBrush="Transparent">
<Grid>
<ContentPresenter x:Name="contentPresenter" ContentTemplate="{TemplateBinding ContentTemplate}"
HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
Margin="4,5,4,4"/>
</Grid>
</Border>
</Grid>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
My buttons:
<dxwuii:SplitPanel Margin="0,10,10,10" HorizontalAlignment="Right" Grid.Column="2" ItemSpacing="0" Orientation="Horizontal" ItemSizeMode="AutoSize" >
<Button Command="{Binding SendViewModelNameCommand, Mode=OneTime}" CommandParameter="AccountTablesViewModel" Style="{StaticResource LocalButtonTemplate}">Express Tables</Button>
<Button Command="{Binding SendViewModelNameCommand, Mode=OneTime}" CommandParameter="MappingViewModel" Style="{StaticResource LocalButtonTemplate}">Item Mapping</Button>
<Button Command="{Binding SendViewModelNameCommand, Mode=OneTime}" CommandParameter="ReportsViewModel" Style="{StaticResource LocalButtonTemplate}">Reports</Button>
<Button Command="{Binding SendViewModelNameCommand, Mode=OneTime}" CommandParameter="PostBalancesViewModel" Style="{StaticResource LocalButtonTemplate}">Post Balances</Button>
</dxwuii:SplitPanel>
Dependency Property Class:
namespace MyAppName.Model
{
public class StateManager : DependencyObject
{
public static string GetVisualStateProperty(DependencyObject obj)
{
return (string)obj.GetValue(VisualStatePropertyProperty);
}
public static void SetVisualStateProperty(DependencyObject obj, string value)
{
obj.SetValue(VisualStatePropertyProperty, value);
}
public static readonly DependencyProperty VisualStatePropertyProperty =
DependencyProperty.RegisterAttached(
"VisualStateProperty",
typeof(string),
typeof(StateManager),
new PropertyMetadata((dependencyObject, args) =>
{
var frameworkElement = dependencyObject as FrameworkElement;
if (frameworkElement == null)
return;
VisualStateManager.GoToState(frameworkElement, (string)args.NewValue, true);
}));
}
}
Set Tag and Attached property on your each button as below. Tag value will be the VisualState value to which button should go on click.
<Button Tag="AcountTables" local:StateManager.VisualStateProperty="{Binding YOURVIEWMODELPROPERTY}" Command="{Binding SendViewModelNameCommand, Mode=OneTime}" CommandParameter="AccountTablesViewModel" Style="{StaticResource LocalButtonTemplate}">Express Tables</Button>
Update your AttachedProperty like:
public static readonly DependencyProperty VisualStatePropertyProperty =
DependencyProperty.RegisterAttached(
"VisualStateProperty",
typeof(string),
typeof(StateManager),
new PropertyMetadata((dependencyObject, args) =>
{
var frameworkElement = dependencyObject as FrameworkElement;
if (frameworkElement == null)
return;
if (args.NewValue == frameworkElement.Tag.ToString())
{
VisualStateManager.GoToState(frameworkElement, (string)args.NewValue, true);
}
else
{
VisualStateManager.GoToState(frameworkElement, "Normal", true);
}
}));
I have created a custom button for my application in blend and used its resource in my xaml code.
But i want to use it in my class xyztextbutton.
But unable to o so as.
[ button.Style = (Style)Application.Current.Resources["ButtonStyle1"];]
is not working properly
And I am adding it to a layout-root later on but still not working.
phone:PhoneApplicationPage
x:Class="xyz.MainPage"
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"
mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="768"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="Portrait" Orientation="Portrait"
shell:SystemTray.IsVisible="True" xmlns:toolkit="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Toolkit">
<phone:PhoneApplicationPage.Resources>
<Style x:Key="ButtonStyle1" TargetType="Button">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Grid>
<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="CommonStates">
<VisualState x:Name="Pressed">
<Storyboard>
<ColorAnimation Duration="0" To="#FF216391" Storyboard.TargetProperty="(Shape.Stroke).(SolidColorBrush.Color)" Storyboard.TargetName="path" d:IsOptimized="True"/>
<ColorAnimation Duration="0" To="#FF3E8EBB" Storyboard.TargetProperty="(Shape.Fill).(SolidColorBrush.Color)" Storyboard.TargetName="path" d:IsOptimized="True"/>
</Storyboard>
</VisualState>
<VisualState x:Name="Normal"/>
<VisualState x:Name="Disabled"/>
<VisualState x:Name="MouseOver"/>
</VisualStateGroup>
<VisualStateGroup x:Name="FocusStates">
<VisualState x:Name="Focused"/>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
<Path x:Name="path" Data="M22.729,0 L22.73,0 L107.729,0 L107.729,38 L22.76,38 L22.76,38.031 L-0.483128,19.5199 L22.729,0.000793 z" Stretch="Fill" UseLayoutRounding="False" Stroke="#FFD0E21D" StrokeThickness="2" Fill="#FF5FB4E4" Margin="-0.483,0,0,0"/>
<ContentPresenter HorizontalAlignment="Center" Margin="24,1,4,9" Width="80" Height="30" OpacityMask="Black" VerticalAlignment="Top"/>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</phone:PhoneApplicationPage.Resources>
<!--LayoutRoot is the root grid where all page content is placed-->
<Grid x:Name="LayoutRoot" Background="White" Height="800">
<Grid.RowDefinitions>
<!--<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>-->
</Grid.RowDefinitions>
</Grid>
public class xyzTextButton
{
private int ScreenWidth = Convert.ToInt32(Application.Current.Host.Content.ActualWidth);
private int ScreenHeight = Convert.ToInt32(Application.Current.Host.Content.ActualHeight);
Grid uiGrid = null;
Image image = null;
TextBlock textblock = null;
Button button = null;
Dictionary<string, object> actions = null;
public void CreateTextButton(Dictionary<string, object> dict, Grid grid, string pagename)
{
uiGrid = new Grid();
image = new Image();
button = new Button();
button.Style = (Style)Application.Current.Resources["ButtonStyle1"];
textblock = new TextBlock();
Boolean autoresizesSubviews = Convert.ToBoolean(ObjectForKey("autoresizesSubviews", dict));
actions = (Dictionary<string, object>)ObjectForKey("actions", dict);
}
}
As far as i know it should work.
Ok, how about changing the whole method?
How about developing Custom User Control, just copy-paste your XAML, name it MyButton, and use as a ordinary button:
MyButton a = new MyButton();
How to add labels with sum for column. I need to do that with chart stacked series from silverlight toolkit
Was created custom StackedColumnSeriesEx!
Here you should find define that we are using new custom data points type and we can find sum of datapoints values. Also we should define which datapoint is located TOP most in StackedColumnSeries:
public class StackedColumnSeriesEx : StackedColumnSeries
{
protected override DataPoint CreateDataPoint()
{
// Custom data point with new fields.
return new CustomDataPoint();
}
protected override void UpdateDataItemPlacement(IEnumerable<DataItem> dataItems)
{
// Calculate sum here.
foreach (var group in this.IndependentValueGroups)
{
decimal sum = 0;
foreach (var dataItem in group.DataItems)
{
double currentValue = 0;
if (ValueHelper.TryConvert(dataItem.ActualDependentValue, out currentValue))
{
sum += Convert.ToDecimal(currentValue);
}
}
// Set sum and find most top point
foreach (DataItem dataItem in group.DataItems)
{
int index = group.DataItems.IndexOf(dataItem);
var convertedDataItem = dataItem.DataPoint as CustomDataPoint;
if (convertedDataItem == null)
{
continue;
}
convertedDataItem.SeriesDefinition = dataItem.SeriesDefinition;
convertedDataItem.IsTopPoint = index + 1 == group.DataItems.Count();
convertedDataItem.DependentValueSum = sum;
}
}
base.UpdateDataItemPlacement(dataItems);
}
}
New CustomDataPoint with few new dependency properies
IsTopPoint - bool value indicating whether current point is top most point!
DependentValueSum - double value to display. Dependency property
New style of CustomDataPoint to draw text DependentValueSum in case if its most top value:
`
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="local:CustomDataPoint">
<Grid x:Name="Root"
Opacity="0">
<ToolTipService.ToolTip>
<ToolTip BorderThickness="0"
DataContext="{Binding RelativeSource={RelativeSource TemplatedParent}}"
Background="Transparent"
BorderBrush="Transparent">
<ToolTip.Template>
<ControlTemplate TargetType="ToolTip">
<Charts:ExpensesToolTip HorizontalAlignment="Stretch"
VerticalAlignment="Stretch" />
</ControlTemplate>
</ToolTip.Template>
</ToolTip>
</ToolTipService.ToolTip>
<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="CommonStates">
<VisualStateGroup.Transitions>
<VisualTransition GeneratedDuration="0:0:0.1" />
</VisualStateGroup.Transitions>
<VisualState x:Name="Normal" />
<VisualState x:Name="MouseOver" />
</VisualStateGroup>
<VisualStateGroup x:Name="SelectionStates">
<VisualStateGroup.Transitions>
<VisualTransition GeneratedDuration="0:0:0.1" />
</VisualStateGroup.Transitions>
<VisualState x:Name="Unselected" />
<VisualState x:Name="Selected" />
</VisualStateGroup>
<VisualStateGroup x:Name="RevealStates">
<VisualStateGroup.Transitions>
<VisualTransition GeneratedDuration="0:0:0.5" />
</VisualStateGroup.Transitions>
<VisualState x:Name="Shown">
<Storyboard>
<DoubleAnimation Duration="0"
To="1"
Storyboard.TargetProperty="Opacity"
Storyboard.TargetName="Root" />
</Storyboard>
</VisualState>
<VisualState x:Name="Hidden">
<Storyboard>
<DoubleAnimation Duration="0"
To="0"
Storyboard.TargetProperty="Opacity"
Storyboard.TargetName="Root" />
</Storyboard>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups><TextBlock Text="{TemplateBinding DependentValuesSum}"
VerticalAlignment="Top" Margin="-2,-21,0,0" TextAlignment="Center"
Visibility="{Binding IsTopPoint, Converter={StaticResource VisibilityConverter}, RelativeSource={RelativeSource TemplatedParent}}"
HorizontalAlignment="Center" />
<Grid x:Name="grid"
Background="{TemplateBinding Background}">
<Grid.OpacityMask>
<LinearGradientBrush EndPoint="0.5,1"
StartPoint="0.5,0">
<GradientStop Color="#87FFFFFF" />
<GradientStop Color="#D6FFFFFF"
Offset="1" />
</LinearGradientBrush>
</Grid.OpacityMask>
</Grid>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>`