I'm developing a UWP app and trying to apply a style per control in code that would set the Grid.Column property, effectively to move the elements around the grid. However, my elements stay where they are, even though the animations run. Any setter besides Grid.* works, and I can see the styles being applied both through my code and through the live property window.
I know there are other ways to accomplish what I'm going for and I'll probably do one of those, but I want to know what's going on here. I'll post a sample of my page and the command that applies the styling:
MainPage.xaml
<Page
x:Class="UWPApp.Scorekeeper.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:UWPApp.Scorekeeper"
xmlns:viewmodels="using:UWPApp.Scorekeeper.Models.ViewModels"
xmlns:converters="using:UWPApp.Scorekeeper.Converters"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:mo="using:UWPApp.Scorekeeper.Models"
mc:Ignorable="d"
x:Name="MainPageElement"
d:DesignHeight="600"
d:DesignWidth="1024">
<Page.Resources>
<DataTemplate x:Key="GridHorizontalTemplate" x:DataType="local:MainPage">
<Grid MinWidth="768" MinHeight="500" Background="{ThemeResource SystemControlBackgroundAccentBrush}" ManipulationMode="All">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="69*"/>
<ColumnDefinition Width="76*"/>
<ColumnDefinition Width="76*"/>
<ColumnDefinition Width="69*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="73*"/>
<RowDefinition Height="135*"/>
<RowDefinition Height="69*"/>
<RowDefinition Height="43*"/>
</Grid.RowDefinitions>
<Button Foreground="{ThemeResource SystemControlForegroundChromeMediumBrush}" Command="{Binding ElementName=MainPageElement, Path=EnterGoalCommand}" CommandParameter="{Binding ElementName=MainPageElement,Path=StateModel.HomeID}" x:Name="HomeGoalBtn" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Grid.Row="1" Grid.Column="1" Margin="0,0.4,0,0" d:LayoutOverrides="LeftMargin, RightMargin" >
<Button.Resources>
<Style x:Key="FlippedStyle" TargetType="Button">
<Setter Property="Grid.Column" Value="2"/>
</Style>
<Storyboard x:Key="ToFlipAnimation">
<RepositionThemeAnimation FromHorizontalOffset="-487"/>
</Storyboard>
<Storyboard x:Key="FromFlipAnimation">
<RepositionThemeAnimation FromHorizontalOffset="487"/>
</Storyboard>
</Button.Resources>
<Viewbox Margin="40" Stretch="Uniform">
<TextBlock Text="Goal" FontSize="48" FontWeight="Bold" HorizontalAlignment="Center" VerticalAlignment="Bottom" />
</Viewbox>
</Button>
<Button Foreground="{ThemeResource SystemControlForegroundChromeMediumBrush}" Command="{Binding ElementName=MainPageElement, Path=EnterGoalCommand}" CommandParameter="{Binding ElementName=MainPageElement,Path=StateModel.AwayID}" x:Name="AwayGoalBtn" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Grid.Row="1" Grid.Column="2" Margin="0,0.4,-0.2,0" d:LayoutOverrides="LeftMargin, RightMargin" >
<Button.Resources>
<Style x:Key="FlippedStyle" TargetType="Button">
<Setter Property="Grid.Column" Value="1"/>
</Style>
<Storyboard x:Key="ToFlipAnimation">
<RepositionThemeAnimation FromHorizontalOffset="487"/>
</Storyboard>
<Storyboard x:Key="FromFlipAnimation">
<RepositionThemeAnimation FromHorizontalOffset="-487"/>
</Storyboard>
</Button.Resources>
<Viewbox Margin="40" Stretch="Uniform">
<TextBlock Text="Goal" FontSize="48" FontWeight="Bold" HorizontalAlignment="Center" VerticalAlignment="Bottom" />
</Viewbox>
</Button>
</Grid>
</DataTemplate>
</Page.Resources>
<ContentPresenter x:Name="MainContent" Margin="0,0,0,0" HorizontalAlignment="Stretch" d:LayoutOverrides="Width, Height" VerticalAlignment="Stretch">
<VisualStateManager.VisualStateGroups>
<VisualStateGroup>
<VisualState>
<VisualState.StateTriggers>
<AdaptiveTrigger MinWindowWidth="1000"></AdaptiveTrigger>
</VisualState.StateTriggers>
<VisualState.Setters>
<Setter Target="MainContent.ContentTemplate" Value="{StaticResource GridHorizontalTemplate}" />
</VisualState.Setters>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
</ContentPresenter>
</Page>
MainPage.xaml.cs
public ICommand FlipScreen => new CommandHandler(() =>
{
if (!flipped)
{
flipped = true;
foreach (var item in this.FindChildren<FrameworkElement>())
{
object styleObject;
if (item.Resources.TryGetValue("FlippedStyle", out styleObject))
{
item.Style = (Style)styleObject;
}
object animationObject;
if (item.Resources.TryGetValue("ToFlipAnimation", out animationObject))
{
Storyboard board = animationObject as Storyboard;
if (board.GetCurrentState() != ClockState.Stopped)
{
board.Stop();
}
foreach (var subitem in board.Children)
{
Storyboard.SetTarget(subitem, item);
}
board.Begin();
}
}
}
else
{
flipped = false;
foreach (var item in this.FindChildren<FrameworkElement>())
{
item.Style = null;
object animationObject;
if (item.Resources.TryGetValue("FromFlipAnimation", out animationObject))
{
Storyboard board = animationObject as Storyboard;
if (board.GetCurrentState() != ClockState.Stopped)
{
board.Stop();
}
foreach (var subitem in board.Children)
{
Storyboard.SetTarget(subitem, item);
}
board.Begin();
}
}
}
});
FindChildren:
public static List<T> FindChildren<T>(this FrameworkElement element) where T : FrameworkElement
{
int childrenCount = VisualTreeHelper.GetChildrenCount(element);
var children = new FrameworkElement[childrenCount];
List<T> list = new List<T>();
for (int i = 0; i < childrenCount; i++)
{
var child = VisualTreeHelper.GetChild(element, i) as FrameworkElement;
children[i] = child;
if (child is T)
list.Add(child as T);
}
for (int i = 0; i < childrenCount; i++)
if (children[i] != null)
{
var subChild = FindChildren<T>(children[i]);
if (subChild != null)
list.AddRange(subChild);
}
return list;
}
Not sure if a default Button Style in the Resources of a Button would actually apply to that Button.
Better set the Style explicitly:
<Button ... >
<Button.Style>
<Style TargetType="Button">
<Setter Property="Grid.Column" Value="2"/>
</Style>
</Button.Style>
<Button.Resources>
...
</Button.Resources>
<Viewbox ...>
...
</Viewbox>
</Button>
Related
As topic mentioned.I want to use only one popup for all button in my application.I don't know how to get what I want.
Here is what my window looks like:
Info 1:
Info 2:
You can see popup appear on wrong position.I know I can position a popup by setting the PlacementTarget.But each Popup has a different value for the placement property.That is the problem.I'm looking another way to do it.
Here is a popup for option 1:
<StackPanel Orientation="Horizontal">
<!--Option 1: text and button-->
<TextBlock Text="Option 1"
Margin="10"
VerticalAlignment="Center" />
<Popup x:Name="popInfo"
PlacementTarget="{Binding ElementName=btnInfoOption1}"
IsOpen="{Binding IsShowInfo1}">
<ContentControl Style="{StaticResource ContentInfoStyle}">
<TextBlock Text="{Binding InfoContent}"
TextWrapping="Wrap"
Foreground="White"
Width="340"
Padding="10"
Margin="30,0,30,5"
FontSize="15" />
</ContentControl>
</Popup>
<Button x:Name="btnInfoOption1"
Style="{StaticResource btnIcons}"
Background="#0063b1"
Width="30"
Height="30"
Margin="10,10,20,10"
Command="{Binding CmdShowInfo, Delay=1500}"
Tag="{StaticResource ic_ginfo}" />
</StackPanel>
popup for option 2:
<StackPanel Orientation="Horizontal">
<!--Option 2: text and button-->
<TextBlock Text="Option 2"
Margin="10"
VerticalAlignment="Center" />
<Button x:Name="btnOption2"
Style="{StaticResource btnIcons}"
Background="#0063b1"
Width="30"
Height="30"
Margin="10,10,20,10"
Command="{Binding CmdShowInfo, Delay=1500}"
Tag="{StaticResource ic_ginfo}" />
</StackPanel>
ContentControl Style:
<Style TargetType="{x:Type ContentControl}"
x:Key="ContentInfoStyle">
<Setter Property="ContentTemplate">
<Setter.Value>
<DataTemplate>
<Border Background="Green"
CornerRadius="3"
Padding="10,0,12,10">
<StackPanel>
<Button HorizontalAlignment="Right"
Tag="{StaticResource ic_gclear}"
Style="{StaticResource btnIcons}"
Background="White"
Margin="10,5,12,5"
Command="{Binding DataContext.CmdCloseInfo}"
Height="24" />
<ContentPresenter x:Name="content"
TextBlock.FontSize="14"
TextBlock.Foreground="White"
TextBlock.FontFamily="Arial"
Content="{TemplateBinding ContentControl.Content}" />
</StackPanel>
</Border>
</DataTemplate>
</Setter.Value>
</Setter>
</Style>
Button icon style:
<Style TargetType="Button"
x:Key="btnIcons">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Border x:Name="brd" Background="Transparent"
SnapsToDevicePixels="True">
<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="CommonStates">
<VisualState x:Name="Normal" />
<VisualState x:Name="MouseOver" />
<VisualState x:Name="Pressed" />
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
<Path Stretch="Uniform" VerticalAlignment="Center"
Fill="{TemplateBinding Background}"
Data="{TemplateBinding Tag}" />
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
ViewModel.cs:
the content of popup:
private string _InfoContent;
public string InfoContent
{
get { return _InfoContent; }
set
{
if (value != _InfoContent)
{
_InfoContent = value;
OnRaise("InfoContent");
}
}
}
show the popup for option2 and option1:
private bool _IsShowInfo2;
public bool IsShowInfo2
{
get { return _IsShowInfo2; }
set
{
if (value != _IsShowInfo2)
{
_IsShowInfo2 = value;
OnRaise("IsShowInfo2");
}
}
}
//show the popup for option1
private bool _IsShowInfo1;
public bool IsShowInfo1
{
get { return _IsShowInfo1; }
set
{
if (value != _IsShowInfo1)
{
_IsShowInfo1 = value;
OnRaise("IsShowInfo1");
}
}
}
the command for button:
private ICommand _CmdShowInfo;
public ICommand CmdShowInfo
{
get
{
_CmdShowInfo = _CmdShowInfo ?? new RelayCommand(x => this.ShowInfo(true, 1), () => true);
return _CmdShowInfo;
}
}
private ICommand _CmdShowInfo2;
public ICommand CmdShowInfo2
{
get
{
_CmdShowInfo2 = _CmdShowInfo2 ?? new RelayCommand(x => this.ShowInfo(true, 0), () => true);
return _CmdShowInfo2;
}
}
private void ShowInfo(bool show = true, byte option = 0)
{
if (option == 0)
{
this.InfoContent = "Option 1...";
}
else if (option == 1)
{
this.InfoContent = "Option 2...";
}
this.IsShowInfo1 = show;
}
My initial thought was to do this with a styled HeaderedContentControl, but then you've got the icon fill color and the icon data, and I'd have had to add attached properties for those. Once you go there, you may as well just write a custom control.
The dependency properties of IconPopupButton can be bound like any dependency property:
<hec:IconPopupButton
IsOpen="{Binding IsShowInfo1}"
IconFill="YellowGreen"
Content="Another Test Popup"
IconData="M -10,-10 M 0,3 L 17,20 L 20,17 L 3,0 Z M 0,0 L 0,20 L 20,20 L 20,0 Z"
/>
If you want to parameterize the Style applied to the ContentControl in the Popup, add another dependency property. You'll need to give that some thought, though, because you need that ToggleButton to be bound to IsOpen on the templated parent, one way or another. Perhaps you could bind it to the viewmodel property that's bound to the popup button's IsOpen. There's always a way.
So here's that. With snippets to create dependency properties, this is pretty much just a fill-in-the-blanks exercise. Much less to it than meets the eye.
IconPopupButton.cs
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Media;
namespace HollowEarth.Controls
{
public class IconPopupButton : ContentControl
{
static IconPopupButton()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(IconPopupButton), new FrameworkPropertyMetadata(typeof(IconPopupButton)));
}
#region IconData Property
public Geometry IconData
{
get { return (Geometry)GetValue(IconDataProperty); }
set { SetValue(IconDataProperty, value); }
}
public static readonly DependencyProperty IconDataProperty =
DependencyProperty.Register("IconData", typeof(Geometry), typeof(IconPopupButton),
new PropertyMetadata(null));
#endregion IconData Property
#region IconFill Property
public Brush IconFill
{
get { return (Brush)GetValue(IconFillProperty); }
set { SetValue(IconFillProperty, value); }
}
public static readonly DependencyProperty IconFillProperty =
DependencyProperty.Register("IconFill", typeof(Brush), typeof(IconPopupButton),
new PropertyMetadata(SystemColors.ControlTextBrush));
#endregion IconFill Property
#region IsOpen Property
public bool IsOpen
{
get { return (bool)GetValue(IsOpenProperty); }
set { SetValue(IsOpenProperty, value); }
}
public static readonly DependencyProperty IsOpenProperty =
DependencyProperty.Register("IsOpen", typeof(bool), typeof(IconPopupButton),
new PropertyMetadata(false));
#endregion IsOpen Property
#region StaysOpen Property
public bool StaysOpen
{
get { return (bool)GetValue(StaysOpenProperty); }
set { SetValue(StaysOpenProperty, value); }
}
public static readonly DependencyProperty StaysOpenProperty =
DependencyProperty.Register("StaysOpen", typeof(bool), typeof(IconPopupButton),
new PropertyMetadata(false));
#endregion StaysOpen Property
#region Placement Property
public PlacementMode Placement
{
get { return (PlacementMode)GetValue(PlacementProperty); }
set { SetValue(PlacementProperty, value); }
}
public static readonly DependencyProperty PlacementProperty =
DependencyProperty.Register("Placement", typeof(PlacementMode), typeof(IconPopupButton),
new PropertyMetadata(PlacementMode.Right));
#endregion Placement Property
}
}
Themes\Shared.xaml
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:HeaderedPopupTest.Themes"
>
<Geometry x:Key="ic_gclear">M56,4 52,0 28,24 4,0 0,4 24,28 0,52 4,56 28,32 52,56 56,52 32,28Z</Geometry>
<Geometry x:Key="ic_ginfo">M31,0C13.879,0,0,13.879,0,31s13.879,31,31,31s31-13.879,31-31S48.121,0,31,0z M34,46h-6V27.969h6V46z M34,21.969h-6V16h6V21.969z</Geometry>
<Style TargetType="ButtonBase" x:Key="btnIcons">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ButtonBase}">
<Border x:Name="brd" Background="Transparent" SnapsToDevicePixels="True">
<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="CommonStates">
<VisualState x:Name="Normal" />
<VisualState x:Name="MouseOver" />
<VisualState x:Name="Pressed" />
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
<Grid>
<Path
x:Name="Path"
Stretch="Uniform"
VerticalAlignment="Center"
Fill="{TemplateBinding Background}"
Data="{TemplateBinding Tag}"
/>
<TextBlock
x:Name="MissingIconData"
Visibility="Collapsed"
Text="?"
FontWeight="Bold"
FontSize="30"
ToolTip="IconData (Tag) not set"
HorizontalAlignment="Center"
VerticalAlignment="Center"
/>
</Grid>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="Tag" Value="{x:Null}">
<Setter TargetName="MissingIconData" Property="Visibility" Value="Visible" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
Themes\Generic.xaml
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:HeaderedPopupTest.Themes"
xmlns:hec="clr-namespace:HollowEarth.Controls"
>
<ResourceDictionary.MergedDictionaries>
<!-- Change HeaderedPopupTest to the name of your own assembly -->
<ResourceDictionary Source="/HeaderedPopupTest;component/Themes/Shared.xaml" />
</ResourceDictionary.MergedDictionaries>
<Style TargetType="hec:IconPopupButton">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="hec:IconPopupButton">
<Grid x:Name="Grid">
<ToggleButton
x:Name="OpenButton"
Style="{StaticResource btnIcons}"
Background="{TemplateBinding IconFill}"
Tag="{TemplateBinding IconData}"
IsChecked="{Binding IsOpen, RelativeSource={RelativeSource TemplatedParent}, Mode=TwoWay}"
ToolTip="{TemplateBinding ToolTip}"
/>
<Popup
x:Name="Popup"
StaysOpen="{Binding StaysOpen, RelativeSource={RelativeSource TemplatedParent}}"
IsOpen="{Binding IsOpen, RelativeSource={RelativeSource TemplatedParent}, Mode=TwoWay}"
PlacementTarget="{Binding ElementName=ToggleButton}"
Placement="{TemplateBinding Placement}"
>
<Border
Background="Green"
CornerRadius="3"
Padding="10,0,12,10">
<StackPanel>
<ToggleButton
HorizontalAlignment="Right"
Tag="{StaticResource ic_gclear}"
Style="{StaticResource btnIcons}"
Background="White"
Margin="10,5,12,5"
IsChecked="{Binding IsOpen, RelativeSource={RelativeSource TemplatedParent}, Mode=TwoWay}"
Height="24"
/>
<ContentPresenter
x:Name="content"
TextBlock.FontSize="14"
TextBlock.Foreground="White"
TextBlock.FontFamily="Arial"
Content="{TemplateBinding Content}"
/>
</StackPanel>
</Border>
</Popup>
</Grid>
<ControlTemplate.Triggers>
<MultiTrigger>
<MultiTrigger.Conditions>
<!--
I don't understand this: If I use the templated parent's IsOpen,
the effect is as if it were never true.
-->
<Condition SourceName="Popup" Property="IsOpen" Value="True" />
<Condition Property="StaysOpen" Value="False" />
</MultiTrigger.Conditions>
<!--
If StaysOpen is false and the button is enabled while the popup is open,
then clicking on it will cause the popup to flicker rather than close.
-->
<Setter TargetName="OpenButton" Property="IsEnabled" Value="False" />
</MultiTrigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
MainWindow.xaml example usage:
<Window
x:Class="HeaderedPopupTest.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:HeaderedPopupTest"
xmlns:hec="clr-namespace:HollowEarth.Controls"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525"
>
<Window.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Themes\Shared.xaml" />
</ResourceDictionary.MergedDictionaries>
<Style
x:Key="InfoPopupButton"
TargetType="hec:IconPopupButton"
BasedOn="{StaticResource {x:Type hec:IconPopupButton}}"
>
<Setter Property="IconFill" Value="DeepSkyBlue" />
<Setter Property="IconData" Value="{StaticResource ic_ginfo}" />
</Style>
</ResourceDictionary>
</Window.Resources>
<Grid>
<StackPanel
Orientation="Vertical"
HorizontalAlignment="Left"
>
<hec:IconPopupButton
Style="{StaticResource InfoPopupButton}"
Content="This is a test popup"
ToolTip="Test Popup Tooltip"
/>
<hec:IconPopupButton
IconFill="YellowGreen"
Content="Another Test Popup"
IconData="M -10,-10 M 0,3 L 17,20 L 20,17 L 3,0 Z M 0,0 L 0,20 L 20,20 L 20,0 Z"
/>
<hec:IconPopupButton
IconFill="DarkRed"
Content="Missing IconData behavior example"
/>
</StackPanel>
</Grid>
</Window>
You'll notice I changed your buttons to ToggleButton. This is for convenience in wiring them up to the IsOpen property: With a ToggleButton, I just bind IsChecked and I'm done. No need for commands. One side effect of that is that if StaysOpen is false, then when the user clicks on the open button for a Popup, the focus change closes the Popup, which unchecks the button, and then the button gets the mouse message. So the button opens the popup again. This is bizarre behavior from the user's perspective, so you add a trigger to disable the button when the popup is open and StaysOpen is false. When StaysOpen is true, focus change doesn't close the Popup, so you want the button to be enabled in that case.
I changed the btnIcons style to target ButtonBase, so it works identically with Button and ToggleButton.
I am using an expand panel to expand/collapse a list.
My problem is, at a time only one item only in expanded state. In my case if i expand one item without collapsing and i expand other item, then both the list items are in expanded state only, previous expanded item didn,t get collapse.
Refer image. If you see the image, all the 3 items are in expanded state only. Without automatic collapse
Here is my code:
ExpandPanel.cs:
public ExpandPanel()
{
this.DefaultStyleKey = typeof(ExpandPanel);
}
private bool _useTransitions = true;
private VisualState _collapsedState;
public Windows.UI.Xaml.Controls.Primitives.ToggleButton toggleExpander;
private FrameworkElement contentElement;
public static readonly DependencyProperty HeaderContentProperty =
DependencyProperty.Register("HeaderContent", typeof(object),
typeof(ExpandPanel), null);
public static readonly DependencyProperty IsExpandedProperty =
DependencyProperty.Register("IsExpanded", typeof(bool),
typeof(ExpandPanel), new PropertyMetadata(true, IsExpanded_Changed));
public static readonly DependencyProperty CornerRadiusProperty =
DependencyProperty.Register("CornerRadius", typeof(CornerRadius),
typeof(ExpandPanel), null);
public object HeaderContent
{
get { return GetValue(HeaderContentProperty); }
set { SetValue(HeaderContentProperty, value); }
}
public bool IsExpanded
{
get { return (bool)GetValue(IsExpandedProperty); }
set { SetValue(IsExpandedProperty, value); }
}
public CornerRadius CornerRadius
{
get { return (CornerRadius)GetValue(CornerRadiusProperty); }
set { SetValue(CornerRadiusProperty, value); }
}
private static void IsExpanded_Changed(DependencyObject sender, DependencyPropertyChangedEventArgs args)
{
var panel = (ExpandPanel)sender;
panel.changeVisualState(false);
}
public void changeVisualState(bool useTransitions)
{
if (IsExpanded)
{
if (contentElement != null)
{
contentElement.Visibility = Visibility.Visible;
}
VisualStateManager.GoToState(this, "Expanded", useTransitions);
}
else
{
VisualStateManager.GoToState(this, "Collapsed", useTransitions);
_collapsedState = (VisualState)GetTemplateChild("Collapsed");
if (_collapsedState == null)
{
if (contentElement != null)
{
contentElement.Visibility = Visibility.Collapsed;
}
}
}
}
protected override void OnApplyTemplate()
{
base.OnApplyTemplate();
toggleExpander = (Windows.UI.Xaml.Controls.Primitives.ToggleButton)
GetTemplateChild("ExpandCollapseButton");
if (toggleExpander != null)
{
toggleExpander.Click += (object sender, RoutedEventArgs e) =>
{
IsExpanded = !IsExpanded;
toggleExpander.IsChecked = IsExpanded;
changeVisualState(_useTransitions);
};
}
contentElement = (FrameworkElement)GetTemplateChild("Content");
if (contentElement != null)
{
_collapsedState = (VisualState)GetTemplateChild("Collapsed");
if ((_collapsedState != null) && (_collapsedState.Storyboard != null))
{
_collapsedState.Storyboard.Completed += (object sender, object e) =>
{
contentElement.Visibility = Visibility.Collapsed;
};
}
}
changeVisualState(false);
}
xaml code:
<Grid Grid.Row="2">
<Border BorderThickness="2" BorderBrush="White" Background="Black" Margin="5,5,5,0" CornerRadius="5">
<local:ExpandPanel x:Name="weekExpandPanel" HeaderContent="வார பலன்கள்" Foreground="White" Margin="10,0,0,0" IsExpanded="False" FontWeight="ExtraBold">
<local:ExpandPanel.Content>
<TextBlock x:Name="weekAstrology" TextWrapping="Wrap" FontWeight="Normal"></TextBlock>
</local:ExpandPanel.Content>
</local:ExpandPanel>
</Border>
</Grid>
<Grid Grid.Row="3">
<Border BorderThickness="2" BorderBrush="White" Background="Black" Margin="5,5,5,0" CornerRadius="5">
<local:ExpandPanel x:Name="monthExpandPanel" HeaderContent="தமிழ் மாத ஜோதிடம்" Foreground="White" Margin="10,0,0,0" IsExpanded="False" FontWeight="ExtraBold">
<local:ExpandPanel.Content>
<TextBlock x:Name="monthlyAstrology" TextWrapping="Wrap" FontWeight="Normal"></TextBlock>
</local:ExpandPanel.Content>
</local:ExpandPanel>
</Border>
</Grid>
<Grid Grid.Row="4">
<Border BorderThickness="2" BorderBrush="White" Background="Black" Margin="5,5,5,0" CornerRadius="5">
<local:ExpandPanel x:Name="yearExpandPanel" HeaderContent="ஆண்டு பலன்" Foreground="White" Margin="10,0,0,0" IsExpanded="False" FontWeight="ExtraBold">
<local:ExpandPanel.Content>
<TextBlock x:Name="yearlyAstrology" TextWrapping="Wrap" FontWeight="Normal"></TextBlock>
</local:ExpandPanel.Content>
</local:ExpandPanel>
</Border>
</Grid>
.cs file:
weekAstrology.Text= "test";
monthlyAstrology.Text= "test1";
yearlyAstrology.Text= rootObject["ZodiacSignDetails"][0]["Astrotextyearly"].ToString();
my xaml code of custom control:
<Style TargetType="local:ExpandPanel" >
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="local:ExpandPanel">
<Grid>
<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="ViewStates">
<VisualStateGroup.Transitions>
<VisualTransition GeneratedDuration="0:0:0.5"/>
</VisualStateGroup.Transitions>
<VisualState x:Name="Expanded">
<Storyboard>
<DoubleAnimation Storyboard.TargetName="ContentScaleTransform"
Storyboard.TargetProperty="ScaleY" To="1" Duration="0"/>
<DoubleAnimation Storyboard.TargetName="RotateButtonTransform"
Storyboard.TargetProperty="Angle" To="180" Duration="0"/>
</Storyboard>
</VisualState>
<VisualState x:Name="Collapsed">
<Storyboard>
<DoubleAnimation Storyboard.TargetName="ContentScaleTransform"
Storyboard.TargetProperty="ScaleY" To="0" Duration="0"/>
<DoubleAnimation Storyboard.TargetName="RotateButtonTransform"
Storyboard.TargetProperty="Angle" To="0" Duration="0"/>
</Storyboard>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
<Border BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}"
CornerRadius="{TemplateBinding CornerRadius}"
Background="{TemplateBinding Background}">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid Margin="3">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<ContentPresenter Grid.Column="0" VerticalAlignment="Center" Content="{TemplateBinding HeaderContent}" FontSize="16"/>
<ToggleButton Grid.Column="1" RenderTransformOrigin="0.5,0.5" x:Name="ExpandCollapseButton">
<ToggleButton.Template>
<ControlTemplate>
<Grid>
<Ellipse Width="35" Height="35" Fill="{ThemeResource ToggleSwitchCurtainBackgroundThemeBrush}" Margin="0,0,0,0"/>
<Path RenderTransformOrigin="0.5,0.5" HorizontalAlignment="Center" VerticalAlignment="Center"
Data="M2,3L9,10 16,3" Stroke="{ThemeResource ToggleButtonCheckedForegroundThemeBrush}" StrokeThickness="4" Margin="0,0,0,0"/>
</Grid>
</ControlTemplate>
</ToggleButton.Template>
<ToggleButton.RenderTransform>
<RotateTransform x:Name="RotateButtonTransform"/>
</ToggleButton.RenderTransform>
</ToggleButton>
</Grid>
<ContentPresenter Grid.Row="1" Margin="5" Content="{TemplateBinding Content}" x:Name="Content">
<ContentPresenter.RenderTransform>
<ScaleTransform x:Name="ContentScaleTransform"/>
</ContentPresenter.RenderTransform>
</ContentPresenter>
</Grid>
</Border>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
How to collapse one item if i click on other item.
Any help will be highly appreciated.
Thank you.
How to collapse one item if i click on other item. Any help will be highly appreciated.
The easiest way is to register an ExpandStateChanged event for your custom control and collapse other ExpandPanel when any ExpandPanel expands.
You can follow the steps below to achieve this:
Register the ExpandStateChanged event in your custom control and invoke the event in IsExpanded's Setter(ExpandPanel.cs):
public sealed class ExpandPanel : ContentControl
{
public event EventHandler ExpandStateChanged;
...
public bool IsExpanded
{
get { return (bool)GetValue(IsExpandedProperty); }
set
{
SetValue(IsExpandedProperty, value);
if (ExpandStateChanged != null)
{
ExpandStateChanged(this,null);
}
}
}
}
Code the EventHandler in code-behind (MainPage.xaml.cs):
private void ExpandStateChangedHandler(object sender, EventArgs e)
{
var currentPanel = (ExpandPanel)sender;
if (currentPanel.IsExpanded == false)
{
return;
}
foreach(var panel in panels)
{
if (panel.Name != currentPanel.Name)
{
panel.IsExpanded = false;
}
}
}
Register the EventHandler ExpandStateChanged="ExpandStateChangedHandler" in Xaml (MainPage.xaml):
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Grid.RowDefinitions>
<RowDefinition Height="1*"/>
<RowDefinition Height="1*"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid Grid.Row="0">
<Border BorderThickness="2" BorderBrush="White" Background="Black" Margin="5,5,5,0" CornerRadius="5">
<local:ExpandPanel x:Name="weekExpandPanel" HeaderContent="This is Header" Foreground="White" Margin="10,0,0,0" IsExpanded="False" FontWeight="ExtraBold" ExpandStateChanged="ExpandStateChangedHandler">
<local:ExpandPanel.Content>
<TextBlock x:Name="weekAstrology" TextWrapping="Wrap" FontWeight="Normal"></TextBlock>
</local:ExpandPanel.Content>
</local:ExpandPanel>
</Border>
</Grid>
<Grid Grid.Row="1">
<Border BorderThickness="2" BorderBrush="White" Background="Black" Margin="5,5,5,0" CornerRadius="5">
<local:ExpandPanel x:Name="monthExpandPanel" HeaderContent="தமிழ் மாத ஜோதிடம்" Foreground="White" Margin="10,0,0,0" IsExpanded="False" FontWeight="ExtraBold" ExpandStateChanged="ExpandStateChangedHandler">
<local:ExpandPanel.Content>
<TextBlock x:Name="monthlyAstrology" TextWrapping="Wrap" FontWeight="Normal"></TextBlock>
</local:ExpandPanel.Content>
</local:ExpandPanel>
</Border>
</Grid>
<Grid Grid.Row="2">
<Border BorderThickness="2" BorderBrush="White" Background="Black" Margin="5,5,5,0" CornerRadius="5">
<local:ExpandPanel x:Name="yearExpandPanel" HeaderContent="ஆண்டு பலன்" Foreground="White" Margin="10,0,0,0" IsExpanded="False" FontWeight="ExtraBold" ExpandStateChanged="ExpandStateChangedHandler">
<local:ExpandPanel.Content>
<TextBlock x:Name="yearlyAstrology" TextWrapping="Wrap" FontWeight="Normal"></TextBlock>
</local:ExpandPanel.Content>
</local:ExpandPanel>
</Border>
</Grid>
Here is the result:
Here is the complete sample: ExpandCollapseSample
Can someone point on my mistake pleas.
When I add Tabs each tab duplicates data in textboxes that was added in first created tab. ObservableCollection only gets first item in it for each Tab.
I have MainView with TabControl for wich I add Tabs programmatically and set content for them through button_click
<Window x:Class="Test.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:y="clr-namespace:Test"
Title="MainWindow" Height="350" Width="525">
<Grid>
<ToolBar Height="40" VerticalAlignment="Top">
<Button Foreground="AliceBlue" FontWeight="Normal" Click="Button_Click" FontSize="14" FontFamily="Fixed Miriam Transparent">Menu
<Button.ContextMenu>
<ContextMenu >
<MenuItem Header="Add Invoice" Click="AddInvoice_Click"/>
<MenuItem Header="Invoices List" Click="InvoicesList_Click"/>
</ContextMenu>
</Button.ContextMenu>
</Button>
<ToolBar.Background>
<LinearGradientBrush EndPoint="1,0.5" StartPoint="0,0.5">
<GradientStop Color="Black" Offset="0" />
<GradientStop Color="#FF173ADE" Offset="0.431" />
<GradientStop Color="#FF0B1D6F" Offset="0.646" />
</LinearGradientBrush>
</ToolBar.Background>
</ToolBar>
<DockPanel Margin="2,46,0,0" Name="dockPanel1" Width="Auto">
<Grid>
<TabControl Name="tabCon"
>
</TabControl>
</Grid >
</DockPanel>
</Grid>
Through button_click I add Tabs, setting content for them and Datacontext for controls
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
MVM mvm = new MVM();
MVM2 mvm2 = new MVM2();
private void Button_Click(object sender, RoutedEventArgs e)
{
(sender as Button).ContextMenu.IsEnabled = true;
(sender as Button).ContextMenu.PlacementTarget = (sender as Button);
(sender as Button).ContextMenu.Placement = System.Windows.Controls.Primitives.PlacementMode.Bottom;
(sender as Button).ContextMenu.IsOpen = true;
}
private void AddInvoice_Click(object sender, RoutedEventArgs e)
{
mvm2.Invoice_Items.Add(new VM2());
mvm.Itemz.Add(new VM());
var tabItem = new TabItem();
TabView tv = new TabView();
tabItem.Content = tv;
string s = string.Format("Tab");
mvm.Itemz.Add(new VM(s));
xmx.Itemz.Add(new VM());
tv.dataGrid1.DataContext = mvm2;
tv.listBox1.DataContext = mvm;
tabCon.Items.Add(tabItem);
if (tabCon.SelectedIndex == null)
{
tabCon.SelectedIndex = -1;
}
tabCon.SelectedIndex++;
}
}
}
This is view for Tabs
<UserControl x:Class="Test.TabView"
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"
xmlns:views="clr-namespace:Test"
mc:Ignorable="d"
d:DesignHeight="600" d:DesignWidth="800">
<Grid >
<Grid.RowDefinitions>
<RowDefinition Height="*" MinHeight="300" />
<RowDefinition Height="*" MinHeight="300" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<DataGrid AutoGenerateColumns="False" Grid.ColumnSpan="5" Grid.Row="3"
Height="104" HorizontalAlignment="Stretch" Margin="55,115,55,0" Name="dataGrid1"
VerticalAlignment="Top" Width="Auto" CanUserResizeRows="True" ItemsSource="{Binding Path = Invoice_Items}"
IsReadOnly="False" SelectionUnit="Cell" CanUserAddRows="True" IsSynchronizedWithCurrentItem="True">
<DataGrid.Columns>
<DataGridTextColumn Header="Item Name" Binding="{Binding Item_Name, Mode=TwoWay}"/>
</DataGrid.Columns>
</DataGrid>
<ListBox ItemsSource="{Binding Itemz}" SelectedIndex="{Binding SelectedTabIndex, Mode=TwoWay}" ScrollViewer.HorizontalScrollBarVisibility="Disabled" HorizontalAlignment="Stretch" Name="listBox1" VerticalAlignment="Top" IsEnabled="True" Focusable="True" SelectionMode="Single" VerticalContentAlignment="Stretch" MinWidth="768" MinHeight="446" Opacity="1" HorizontalContentAlignment="Stretch">
<ListBox.BorderBrush>
<SolidColorBrush />
</ListBox.BorderBrush>
<ListBox.ItemTemplate>
<DataTemplate>
<views:DataGrrr></views:DataGrrr>
</DataTemplate>
</ListBox.ItemTemplate>
<ListBox.Background>
<SolidColorBrush />
</ListBox.Background>
<ListBox.Resources>
<Style TargetType="{x:Type ListBoxItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ListBoxItem}">
<Border x:Name="Bd"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}"
Background="{TemplateBinding Background}"
Padding="{TemplateBinding Padding}"
SnapsToDevicePixels="true">
<ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"
VerticalAlignment="{TemplateBinding VerticalContentAlignment}" />
</Border>
<ControlTemplate.Triggers>
<MultiTrigger>
<MultiTrigger.Conditions>
<Condition Property="Selector.IsSelectionActive"
Value="False" />
<Condition Property="IsSelected"
Value="True" />
</MultiTrigger.Conditions>
<Setter Property="Background"
TargetName="Bd"
Value="Transparent" />
</MultiTrigger>
<MultiTrigger>
<MultiTrigger.Conditions>
<Condition Property="Selector.IsSelectionActive"
Value="True" />
<Condition Property="IsSelected"
Value="True" />
</MultiTrigger.Conditions>
<Setter Property="Background"
TargetName="Bd"
Value="Transparent" />
</MultiTrigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ListBox.Resources>
</ListBox>
</Grid>
public partial class TabView : UserControl
{
MVM xmx = new MVM();
MVM2 mvm = new MVM2();
public TabView()
{
dataGrid1 = new DataGrid();
InitializeComponent();
//mvm.Invoice_Items.Add(new VM2());
//xmx.Itemz.Add(new VM());
//listBox1.DataContext = xmx;
//dataGrid1.DataContext = mvm;
}
}
And this is view for ListBox
<UserControl x:Class="Test.DataGrrr"
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="456" d:DesignWidth="887">
<Grid Name="grid1" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" MinWidth="768" MinHeight="446" Focusable="True" Height="Auto">
<Grid.RowDefinitions>
<RowDefinition MinHeight="43" Height="*" />
<RowDefinition Height="*" MinHeight="45" />
<RowDefinition Height="*" MinHeight="45" />
<RowDefinition Height="*" MinHeight="170" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" MinWidth="100" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBox Text="{Binding Supplier, Mode=TwoWay}" Grid.Column="1" Height="27" Name="textBox1" VerticalAlignment="Top" Margin="11,6,0,0" HorizontalAlignment="Stretch" Width="Auto" FontSize="14" HorizontalContentAlignment="Stretch" MinWidth="141" FlowDirection="LeftToRight" DataContext="{Binding}" />
<Label Content="Supplier" Height="27" Name="label2" VerticalAlignment="Top" FontSize="14" FontFamily="Tahoma" FontWeight="Bold" Margin="21,6,0,0" Width="Auto" IsEnabled="True" HorizontalAlignment="Stretch" Foreground="Black" Background="White" MinWidth="133" HorizontalContentAlignment="Stretch" />
</Grid>
One of the ObservableCollection
class MVM : BVM
{
private ObservableCollection<VM> items = new ObservableCollection<VM>();
public ObservableCollection<VM> Itemz
{
get
{
return items;
}
set
{
items = value;
OnPropertyChanged("Itemz");
}
}
}
And the model
class VM: BVM
{
private string supplier;
public VM()
{
}
public string Supplier
{
get
{
return supplier;
}
set
{
if (supplier != value)
{
supplier = value;
OnPropertyChanged("Supplier");
}
}
}
}
use list and check result, but i think problem is not in ObservableCollection,
problem is in class thet you binding to tab, it works like if you bind one object to every new tab, like static
I'm trying to make an animated splash screen for my app. I have my MainPage where I show a Popup which has an animation and a textblock. I'd like to change the text of my textblock to show the status of the loading, but I can't change it. Any ideas?
Mainpage code
namespace animatedsplash
{
public partial class MainPage : PhoneApplicationPage
{
BackgroundWorker preloader;
Popup splashPop;
public MainPage()
{
InitializeComponent();
splashPop = new Popup(){IsOpen = true, Child = new Splash() };
preloader = new BackgroundWorker();
RunPreloader();
}
private void RunPreloader()
{
preloader.DoWork += ((s, args) => {
Thread.Sleep(10000);
});
preloader.RunWorkerCompleted += ((s,args) =>
{
this.Dispatcher.BeginInvoke(()=> { this.splashPop.IsOpen = false; });
});
preloader.RunWorkerAsync();
}
}
}
Splash xaml
<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:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity" xmlns:ec="clr-namespace:Microsoft.Expression.Interactivity.Core;assembly=Microsoft.Expression.Interactions" xmlns:eim="clr-namespace:Microsoft.Expression.Interactivity.Media;assembly=Microsoft.Expression.Interactions"
xmlns:local="clr-namespace:animatedsplash"
mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="800"
x:Class="animatedsplash.Splash"
Orientation="Portrait"
shell:SystemTray.IsVisible="False">
<phone:PhoneApplicationPage.Resources>
<Storyboard x:Name="load">
<DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.RenderTransform).(CompositeTransform.Rotation)" Storyboard.TargetName="image">
<EasingDoubleKeyFrame KeyTime="0" Value="-180"/>
<EasingDoubleKeyFrame KeyTime="0:0:1" Value="0"/>
<EasingDoubleKeyFrame KeyTime="0:0:2" Value="180"/>
</DoubleAnimationUsingKeyFrames>
</Storyboard>
</phone:PhoneApplicationPage.Resources>
<phone:PhoneApplicationPage.FontFamily>
<StaticResource ResourceKey="PhoneFontFamilyNormal"/>
</phone:PhoneApplicationPage.FontFamily>
<phone:PhoneApplicationPage.FontSize>
<StaticResource ResourceKey="PhoneFontSizeNormal"/>
</phone:PhoneApplicationPage.FontSize>
<phone:PhoneApplicationPage.Foreground>
<StaticResource ResourceKey="PhoneForegroundBrush"/>
</phone:PhoneApplicationPage.Foreground>
<i:Interaction.Triggers>
<eim:StoryboardCompletedTrigger Storyboard="{StaticResource load}">
<eim:ControlStoryboardAction Storyboard="{StaticResource load}"/>
</eim:StoryboardCompletedTrigger>
<i:EventTrigger>
<eim:ControlStoryboardAction Storyboard="{StaticResource load}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
<!--LayoutRoot is the root grid where all page content is placed-->
<Grid x:Name="LayoutRoot" Background="Transparent">
<!--TitlePanel contains the name of the application and page title--><!--ContentPanel - place additional content here-->
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Image Margin="0" Grid.Row="1" Source="/media/splashbg.jpg" Stretch="Fill" d:IsLocked="True"/>
<Image x:Name="rotator" Margin="96,288,184,312" Grid.Row="1" Source="media/splashpin.png" Stretch="Fill" d:IsLocked="True"/>
<Image x:Name="image" Margin="142,305,0,370" Grid.Row="1" Source="media/pinload.png" Stretch="Fill" HorizontalAlignment="Left" Width="75" RenderTransformOrigin="0.838,0.504">
<Image.RenderTransform>
<CompositeTransform/>
</Image.RenderTransform>
</Image>
<TextBlock x:Name="preloader_percentage" Margin="178,354,0,0" Grid.Row="1" TextWrapping="Wrap" Text="100" VerticalAlignment="Top" RenderTransformOrigin="0.5,0.593" TextAlignment="Right" HorizontalAlignment="Left" Width="35" FontFamily="Segoe WP Semibold" Height="27"/>
<TextBlock Margin="213,354,0,0" Grid.Row="1" TextWrapping="Wrap" Text="%" VerticalAlignment="Top" HorizontalAlignment="Left" Width="16" FontFamily="Segoe WP Semibold" d:IsLocked="True"/>
</Grid>
</phone:PhoneApplicationPage>
How about something like this:
In Splash.xaml.cs you would have the following:
public string Progress
{
get { return preloader_percentage.Text; }
set { preloader_percentage.Text = value; }
}
And in MainWindow.xaml.cs you change your code to look something like this:
preloader.WorkerReportsProgress = true;
preloader.ProgressChanged += (sender, e) =>
{
this.Dispatcher.BeginInvoke(() =>
(this.splashPop.Child as Splash).Progress = e.ProgressPercentage.ToString());
};
Then in your worker method you need to call preloader.ReportProgress() method several times. As far as I know, that should do it.
Note: There are a lot of design landmines here. I'd suggest getting this code to work, and you can refactor later to make it cleaner and easier to maintain.
I have a WPF window with property WindowStyle="SingleBorderWindow".
Now I want to know how to set a button on left upper corner of the window border.
You probably need to use window chrome library which is described here.
I assume this is so you can re-create the Minimize/Maximize/Close buttons.
You have two options, use a Grid or a DockPanel. I have included a sample for a Grid below.
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
<Grid.RowDefinitions>
<StackPanel Orientation="Horizontal" Margin="2,0" HorizontalAlignment="Right" VerticalAlignment="Top">
</StackPanel>
</Grid>
A Grid with a RowDefinition Height="Auto" that has a StackPanel Orientation="Horizontal" that is right-aligned.
However
If you want to make a true border-less window, you will have more work to do than simply setting the WindowStyle to None.
One main stumbling block I encountered was that when WindowStyle is None, it will not respect the task bar (i.e. overlap it) and you will need to hook into the message pump to set the correct window constraints.
Let me know in the comments if you want to know how to do this, will happy post sample code.
You need to make custom window by setting transparency, background and style like below :
<Window x:Class="WpfApplication2.Window2"
Name="Window2xx"
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"
mc:Ignorable="d" xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
Title="window1"
xmlns:m="clr-namespace:WpfApplication2"
AllowsTransparency="True" WindowStyle="None"
WindowStartupLocation="CenterOwner" d:DesignWidth="410" StateChanged="Window_StateChanged"
SizeToContent="WidthAndHeight" ShowInTaskbar="False" Background="Transparent">
<Window.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Style.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Window.Resources>
<Grid>
<m:MasterWindow Width="400">
<m:MasterWindow.WindowTitle>
<ContentPresenter Content="window1" MouseLeftButtonDown="Window_MouseLeftButtonDown"></ContentPresenter>
</m:MasterWindow.WindowTitle>
<m:MasterWindow.Content>
<Grid>
</Grid>
</m:MasterWindow.Content>
</m:MasterWindow>
</Grid>
</Window>
Code behind window2 :
namespace WpfApplication2
{
public partial class Window2 : Window
{
public Window2()
{
InitializeComponent();
}
private void Window_StateChanged(object sender, EventArgs e)
{
if (((Window)sender).WindowState == WindowState.Maximized)
((Window)sender).WindowState = WindowState.Normal;
}
private void Window_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
try
{
DragMove();
}
catch ()
{}
}
}
}
Master window is like below :
namespace WpfApplication2
{
public class MasterWindow : ContentControl
{
public static RoutedCommand CloseWindowCommand;
static MasterWindow()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(MasterWindow), new FrameworkPropertyMetadata(typeof(MasterWindow)));
CloseWindowCommand = new RoutedCommand("CloseWindow", typeof(MasterWindow));
CommandManager.RegisterClassCommandBinding(typeof(MasterWindow), new CommandBinding(CloseWindowCommand, CloseWindowEvent));
}
public static readonly DependencyProperty WindowTitleProperty = DependencyProperty.Register("WindowTitle", typeof(object), typeof(MasterWindow), new UIPropertyMetadata());
public object WindowTitle
{
get { return (object)GetValue(WindowTitleProperty); }
set { SetValue(WindowTitleProperty, value); }
}
private static void CloseWindowEvent(object sender, ExecutedRoutedEventArgs e)
{
MasterWindow control = sender as MasterWindow;
if (control != null)
{
Window objWindow = Window.GetWindow(((FrameworkElement)sender));
if (objWindow != null)
{
if (objWindow.Name.ToLower() != "unlockscreenwindow")
{
Window.GetWindow(((FrameworkElement)sender)).Close();
}
}
}
}
}
}
Styles for master window :
<ResourceDictionary
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"
xmlns:local="clr-namespace:WpfApplication2"
x:Class="MasterWindow">
<Style x:Key="WindowTitle" TargetType="ContentPresenter">
<Setter Property="Control.FontFamily" Value="Segoe UI"></Setter>
<Setter Property="Control.FontSize" Value="14"></Setter>
<Setter Property="Control.FontWeight" Value="SemiBold"></Setter>
<Setter Property="Control.Foreground" Value="White"></Setter>
<Setter Property="Control.VerticalAlignment" Value="Top"></Setter>
<Setter Property="Control.HorizontalAlignment" Value="Left"></Setter>
<Setter Property="Control.VerticalContentAlignment" Value="Top"></Setter>
</Style>
<Style x:Key="closebutton" BasedOn="{x:Null}" TargetType="{x:Type Button}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Grid>
<Rectangle
Opacity="1"
RadiusX="2"
RadiusY="2"
Stroke="#ffffff"
StrokeThickness="1">
<Rectangle.Fill>
<LinearGradientBrush
StartPoint="0.6190476190476191,-0.5"
EndPoint="1.1128888811383928,1.426776123046875">
<LinearGradientBrush.GradientStops>
<GradientStopCollection>
<GradientStop
Color="#2E4C87"
Offset="0" />
<GradientStop
Color="#FFffffff"
Offset="1" />
</GradientStopCollection>
</LinearGradientBrush.GradientStops>
</LinearGradientBrush>
</Rectangle.Fill>
</Rectangle>
<Path
Margin="5,5,5,5"
Stretch="Fill"
Opacity="1"
Data="M 808.8311767578125,278.7662353515625 C808.8311767578125,278.7662353515625 820,268 820,268 "
Stroke="#ffffff"
StrokeThickness="2" />
<Path
Margin="5,5,5,5"
Stretch="Fill"
Opacity="1"
Data="M 809.4155883789062,268.3636474609375 C809.4155883789062,268.3636474609375 820,279 820,279 "
Stroke="#ffffff"
StrokeThickness="2" />
<ContentPresenter SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" RecognizesAccessKey="True"/>
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsFocused" Value="True"/>
<Trigger Property="IsDefaulted" Value="True"/>
<Trigger Property="IsMouseOver" Value="True"/>
<Trigger Property="IsPressed" Value="True"/>
<Trigger Property="IsEnabled" Value="False"/>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style TargetType="{x:Type local:MasterWindow}">
<Setter Property="IsTabStop" Value="False" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:MasterWindow}">
<StackPanel>
<Border x:Name="border" Background="WhiteSmoke" BorderBrush="#2E4C87" BorderThickness="7" CornerRadius="8,8,8,8" >
<Border.BitmapEffect>
<DropShadowBitmapEffect Color="Black" Direction="320" Opacity="0.75" ShadowDepth="8"></DropShadowBitmapEffect>
</Border.BitmapEffect>
<Border.RenderTransform>
<TransformGroup>
<ScaleTransform ScaleX="0.95" ScaleY="0.95"/>
<SkewTransform AngleX="0" AngleY="0"/>
<RotateTransform Angle="0"/>
<TranslateTransform X="0" Y="0"/>
</TransformGroup>
</Border.RenderTransform>
<Border.Triggers>
<EventTrigger RoutedEvent="Border.Loaded">
<BeginStoryboard>
<Storyboard>
<DoubleAnimation Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[0].(ScaleTransform.ScaleX)" From="0" To="0.96" Duration="0:0:0.6"/>
<DoubleAnimation Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[0].(ScaleTransform.ScaleY)" From="0" To="0.96" Duration="0:0:0.6"/>
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</Border.Triggers>
<Grid HorizontalAlignment="Stretch" >
<Grid.RowDefinitions>
<RowDefinition Height="32"></RowDefinition>
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Border BorderThickness="5,5,3,0" Background="#2E4C87" BorderBrush="#2E4C87" CornerRadius="5,4,0,0" VerticalAlignment="Top" Height="32" Margin="-6,-6,-4,0" >
<Grid Background="Transparent" HorizontalAlignment="Stretch" Height="32" VerticalAlignment="Center" >
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="30"/>
</Grid.ColumnDefinitions>
<ContentPresenter Content="{TemplateBinding WindowTitle}" Margin="0,4,0,0" HorizontalAlignment="Stretch" Style="{StaticResource WindowTitle}" />
<Button Name="btnClose" Style="{StaticResource closebutton}" Cursor="Hand" Command="{x:Static local:MasterWindow.CloseWindowCommand}" VerticalAlignment="Top" Height="18" HorizontalAlignment="Right" Width="18" Margin="0,5,8,0" Grid.Column="1" />
</Grid>
</Border>
<Border BorderBrush="Transparent" BorderThickness="7,0,7,7" VerticalAlignment="Top" HorizontalAlignment="Left" CornerRadius="0,0,10,10" Grid.Row="1"></Border>
<ContentPresenter Grid.Row="1" Content="{TemplateBinding Content}" VerticalAlignment="Top" Margin="0,-6,0,0"/>
</Grid>
</Border>
</StackPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>