First, let me show you how my code is cut.
I have this code in a xaml UC (eventsUC.xaml) :
<UserControl x:Class="QuimeO.UserControls.Lists.EventsListUC"
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:ToggleSwitch="clr-namespace:ToggleSwitch;assembly=ToggleSwitch"
mc:Ignorable="d"
Width="477"
>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<ScrollViewer HorizontalScrollBarVisibility="Disabled" Width="auto" VerticalScrollBarVisibility="Auto" HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
<ItemsControl Grid.Row="0" BorderThickness="0" x:Name="eventsList" ScrollViewer.VerticalScrollBarVisibility="Auto" HorizontalContentAlignment="Stretch" ScrollViewer.HorizontalScrollBarVisibility="Disabled">
<ItemsControl.Resources>
<ResourceDictionary x:Name="eventslisttempplate" Source="EventsListTemplate.xaml" />
</ItemsControl.Resources>
</ItemsControl>
</ScrollViewer>...
My EventsListTemplate.xaml looks like this :
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="QuimeO.UserControls.Lists.EventsListTemplate"
xmlns:apiNamespace="clr-namespace:QuimeO.DBO"
>
<DataTemplate DataType="{x:Type apiNamespace:EventsDictionary}">
<StackPanel Orientation="Vertical">
<Border BorderBrush="LightGray" BorderThickness="0,0,0,1" Margin="0,5,0,0">
<TextBlock HorizontalAlignment="Right" Foreground="Gray" Text="{Binding FormatedDate}" FontSize="14"></TextBlock>
</Border>
<ListView Grid.Row="0" x:Name="eventsList" ItemsSource="{Binding Events}" BorderThickness="0" MouseDoubleClick="eventsList_MouseDoubleClick">
</ListView>
</StackPanel>
</DataTemplate>
</ResourceDictionary>
And my EventsListTemplate.xaml.cs code behind looks like this
public partial class EventsListTemplate : ResourceDictionary
{
public Delegate MainWindowControlPointer;
private void eventsList_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
var ev = ((sender as ListView).SelectedItem as ListViewItem).DataContext as Event;
System.Diagnostics.Debug.WriteLine(ev.Name);
this.MainWindowControlPointer.DynamicInvoke(ev.Ancestors.Root, new Element() { Category = ev.Category, Id = ev.Id, Name = ev.Name });
}
}
When I click on an item of my listview in my template, it trigger the eventsList_MouseDoubleCkick and I can retrieve my event.
However, I would like to trigger an action in the UC where the template is created (first source code block).
To do that, I just want to create a delegate in my Template (technicaly, in a perfect world, something like "this.rd_eventslisttemplate.MainWindowControlPointer = ... "). But, I don't know how to do it or if this is even possible.
After encrypting your question for a while I think I got it.
There is a nice method called VisualTreeHelper.GetParent() which gets you the parent of a control in VisualTree.
Now to your problem when you catch your event in EventsListTemplate you will need to call GetParent() few times till you finally get the instance of your UserControl.
Thats it.
Related
I have a UWP application:
My app command bar (XAML 2) manages TabView content (XAML 1). I need different command bars for different tab types. Now I using several frames in second XAML, and I can't change it from XAML 1.
How I can change XAML 2 UI from XAML 1 .cs file?
Thanks for any help.
UPD:
I have main XAML:
<Page
x:Class="Test.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:NetChrom"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:controls="using:Microsoft.Toolkit.Uwp.UI.Controls"
mc:Ignorable="d"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Grid x:Name="BaseGrid">
<Grid.RowDefinitions>
<!-- titlebar -->
<RowDefinition x:Name="Titlebar" Height="30">
</RowDefinition>
<!-- toolbar -->
<RowDefinition x:Name="Toolbar" Height="110">
</RowDefinition>
<!-- main window -->
<RowDefinition>
</RowDefinition>
</Grid.RowDefinitions>
<Grid x:Name="TitlebarGrid" Grid.Row="0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="5*">
</ColumnDefinition>
</Grid.ColumnDefinitions>
<local:TitleBar/>
</Grid>
<Grid x:Name="ToolbarGrid" Grid.Row="1">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="37*">
</ColumnDefinition>
<ColumnDefinition Width="27*"/>
</Grid.ColumnDefinitions>
<!-- toolbar -->
<local:Toolbar Grid.ColumnSpan="2"/>
</Grid>
<!-- content-->
<Grid x:Name="MainContent" Grid.Row="2" Background="AliceBlue">
<Grid.ColumnDefinitions>
<ColumnDefinition MaxWidth="325" MinWidth="120">
</ColumnDefinition>
<ColumnDefinition>
</ColumnDefinition>
</Grid.ColumnDefinitions>
<Grid Grid.Column="1" Background="#F3F3F3">
<local:MainTabbar/>
</Grid>
<Grid Grid.Column="0" Background="LightBlue">
<local:FileManager/>
</Grid>
<controls:GridSplitter
Margin="0,10,10,0"
Opacity="0"
Background="Transparent"
GripperCursor="Default"
HorizontalAlignment="Left"
Grid.Column="1"
ResizeDirection="Auto"
ResizeBehavior="BasedOnAlignment"
CursorBehavior="ChangeOnSplitterHover"
Width="0">
<controls:GridSplitter.RenderTransform>
<TranslateTransform X="-8" />
</controls:GridSplitter.RenderTransform>
</controls:GridSplitter>
</Grid>
</Grid>
</Page>
and in this XAML there are two another XAML: MainTabbar (XAML 1) and Toolbar (XAML 2) from scheme.
This is Toolbar.xaml:
<UserControl
x:Class="Test.Toolbar"
x:Name="toolbarControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:muxc="using:Microsoft.UI.Xaml.Controls"
xmlns:local="using:Test"
xmlns:met="using:Test.Method"
xmlns:chr="using:Test.ChrOptions"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"
d:DesignHeight="110"
d:DesignWidth="1920">
<Border CornerRadius="0,0,10,10" BorderBrush="#D4D4D4" BorderThickness="1,0,1,1" Background="#F3F3F3">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="110">
</RowDefinition>
</Grid.RowDefinitions>
<Grid x:Name="MainGrid">
<Grid.ColumnDefinitions>
<ColumnDefinition>
</ColumnDefinition>
<ColumnDefinition Width="320"/>
</Grid.ColumnDefinitions>
<Grid Grid.Column="1" HorizontalAlignment="Right">
<StackPanel Orientation="Horizontal" Margin="0,0,0,0">
</StackPanel>
</Grid>
<Grid Grid.Column="0">
<Frame x:Name="toolbarFrame"/> <!-- cmdbar frame>
</Grid>
</Grid>
</Grid>
</Border>
</UserControl>
This is MainTabbar:
<Page
x:Class="Test.MainTabbar"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:Test"
xmlns:met="using:Test.Method"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:muxc="using:Microsoft.UI.Xaml.Controls"
mc:Ignorable="d"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"
d:DesignWidth="1595">
<Grid Margin="10,0,0,0">
<muxc:TabView x:Name="Tabs"
IsAddTabButtonVisible="False"
VerticalAlignment="Stretch"
TabCloseRequested="Tabs_TabCloseRequested"
AllowDropTabs="True"
CanDragTabs="False"
CanReorderTabs="True"
TabDroppedOutside="Tabs_TabDroppedOutside"
TabStripDragOver="Tabs_TabStripDragOver"
TabStripDrop="Tabs_TabStripDrop"
TabDragStarting="Tabs_TabDragStarting" >
<muxc:TabView.TabItems>
<muxc:TabViewItem Header="SampleMethod.met" IsClosable="False">
<muxc:TabViewItem.IconSource>
<muxc:SymbolIconSource Symbol="Placeholder" />
</muxc:TabViewItem.IconSource>
<!-- <Frame x:Name="MethodFrame"/> -->
<met:MethodTabView/>
</muxc:TabViewItem>
<muxc:TabViewItem Header="SampleChrome.chr" IsClosable="False">
<muxc:TabViewItem.IconSource>
<muxc:SymbolIconSource Symbol="Placeholder" />
</muxc:TabViewItem.IconSource>
<local:ChrView/>
</muxc:TabViewItem>
</muxc:TabView.TabItems>
<muxc:TabView.TabStripHeader>
<Grid x:Name="ShellTitlebarInset" Background="#F3F3F3" />
</muxc:TabView.TabStripHeader>
<muxc:TabView.TabStripFooter>
<Grid x:Name="CustomDragRegion" Background="#F3F3F3" />
</muxc:TabView.TabStripFooter>
</muxc:TabView>
</Grid>
</Page>
I need to get current tab type in MainTabbar.xaml.cs (it's ok). And then change Command Bar in Toolbar.xaml frame.
I wrote this procedure for change frame in Toolbar.xaml.cs:
public void setMetCmdbarMode()
{
toolbarFrame.Navigate(typeof(MethodToolbar), null);
}
But I don't know how I can call this function from MainTabbar class, or how I can translate tab type to Toolbar class.
After checking your code, you could try to create a custom event in the MainTabbar, and handle it in the MainPage. This event is triggered when the selected item of the TabView is changed. Then you could get notified in the MainPage and call method to change the Toolbar.
Here are the detailed steps:
Create a custom Event named TabItemChanged on the MainTabbar page and call it in the TabView_SelectionChanged event.
Handle the TabItemChanged in the MainPage
Change the content of the Toolbar as you want in the EventHandler based on the TabViewItem.
Code in MainTabbar:
public sealed partial class MainTabbar : Page
{
public event EventHandler TabItemChanged;
public MainTabbar()
{
this.InitializeComponent();
}
private void Tabs_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (this.TabItemChanged != null)
this.TabItemChanged(Tabs.SelectedItem, new EventArgs());
}
}
In the MainPage.Xaml
<local:MainTabbar TabItemChanged="MainTabbar_TabItemChanged"/>
In the MainPage.Xaml.cs
private void MainTabbar_TabItemChanged(object sender, EventArgs e)
{
MUXC.TabViewItem tabitem = sender as MUXC.TabViewItem;
switch (tabitem.Tag)
{
case "123":
Debug.WriteLine("FirstItemSelectecd");
//call method for toobar to change content
//like setMetCmdbarMode()
break;
case "234":
Debug.WriteLine("SecondItemSelectecd");
//call method for toobar to change content
//like setMetCmdbarMode()
break;
}
}
Update:
Give the toolbar a name in MainPage.Xaml
<local:Toolbar x:Name="myToolbar" Grid.ColumnSpan="2"/>
Then call it in the MainPage.Xam.cs:
switch (tabitem.Tag)
{
case "123":
Debug.WriteLine("FirstItemSelectecd");
myToolbar.setMetCmdbarMode();
break;
case "234":
Debug.WriteLine("SecondItemSelectecd");
break;
}
We have a VS extension. The user uses a ToolWindowPane to interact with the extension. The height and width of the ToolWindowPane depends on how the user has their VS environment set up, and currently the contents of the ToolWindowPane does not resize properly.
So here is the window:
public class SymCalculationUtilitiesWindow : ToolWindowPane
{
/// <summary>
/// Initializes a new instance of the <see cref="SymCalculationUtilitiesWindow"/> class.
/// </summary>
public SymCalculationUtilitiesWindow() : base(null)
{
this.Caption = "Sym Calculation Utilities";
this.ToolBar = new CommandID(new Guid(Guids.guidConnectCommandPackageCmdSet), Guids.SymToolbar);
// This is the user control hosted by the tool window; Note that, even if this class implements IDisposable,
// we are not calling Dispose on this object. This is because ToolWindowPane calls Dispose on
// the object returned by the Content property.
this.Content = new UtilitiesView();
}
}
So the UtilitiesView is the default view. Here is the xaml:
<UserControl
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:local="clr-namespace:Sym.VisualStudioExtension" x:Class="Sym.VisualStudioExtension.Engines.UtilitiesView"
xmlns:engines="clr-namespace:Sym.VisualStudioExtension.Engines"
Background="{DynamicResource VsBrush.Window}"
Foreground="{DynamicResource VsBrush.WindowText}"
mc:Ignorable="d"
local:ViewModelLocator.AutoWireViewModel="True"
x:Name="MyToolWindow" Height="800" Width="400">
<UserControl.Resources>
<DataTemplate DataType="{x:Type engines:CalcEngineViewModel}">
<engines:CalcEngineView/>
</DataTemplate>
<DataTemplate DataType="{x:Type engines:TAEngineViewModel}">
<engines:TAEngineView/>
</DataTemplate>
</UserControl.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="auto" />
<RowDefinition Height="207*" />
<RowDefinition Height="593*"/>
</Grid.RowDefinitions>
<Grid x:Name="MainContent"
Grid.Row="1" Grid.RowSpan="2">
<Grid.RowDefinitions>
<RowDefinition Height="auto"/>
<RowDefinition Height="auto"/>
</Grid.RowDefinitions>
<ContentControl Content="{Binding CurrentEngineViewModel}" Grid.RowSpan="2"/>
</Grid>
</Grid>
and the user makes a choice which determines the CurrentEngineViewModel.
The following is the xaml of one of the possible CurrentEngineViewModels:
<UserControl x:Class="Sym.VisualStudioExtension.Engines.CalcEngineView"
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:domain="clr-namespace:Sym.Engines.Calculation.Builder.Domain;assembly=Sym.Engines.Calculation"
xmlns:core="clr-namespace:Sym.Core.Domain;assembly=Sym.Core"
xmlns:helper="clr-namespace:Sym.VisualStudioExtension.Helper_Classes"
xmlns:local="clr-namespace:Sym.VisualStudioExtension"
local:ViewModelLocator.AutoWireViewModel="True"
mc:Ignorable="d"
d:DesignHeight="800" d:DesignWidth="400">
<UserControl.Resources>
<ContextMenu>
...
</ContextMenu>
</UserControl.Resources>
<Grid Margin="-20,-20,-20,-20">
<Grid.RowDefinitions>
<RowDefinition Height="8*"/>
</Grid.RowDefinitions>
<TabControl x:Name="tabControl" HorizontalAlignment="Left" Height="617" Margin="20,54,0,0" VerticalAlignment="Top" Width="357">
<TabItem Header="Calculation Files">
<ListBox Name="CalcFilesListBox"
Margin="20" ItemsSource="{Binding CalcFilesList}"
ContextMenu="{StaticResource NewEditDeleteContextMenu}"
Tag="{x:Type core:CalcFile}">
...
</ListBox>
</TabItem>
<TabItem Header="Template Files" Height="22" VerticalAlignment="Top">
<TreeView ItemsSource="{Binding TemplateFamilyList}"
Margin="20"
ContextMenu="{StaticResource NewEditDeleteContextMenu}"
Tag="{x:Type domain:TemplateParameter}">
<TreeView.Resources>
...
</TreeView.Resources>
</TreeView>
</TabItem>
<TabItem Header="Advanced Calc Files">
<ListBox Margin="20"
ItemsSource="{Binding AdvancedCalcFilesList}"
ContextMenu="{StaticResource NewEditDeleteContextMenu}"
Tag="{x:Type domain:TemplateCalculation}">
...
</ListBox>
</TabItem>
</TabControl>
<Label x:Name="label" Content="{Binding Path=Title}" HorizontalAlignment="Left" Height="27" Margin="10,22,0,0" VerticalAlignment="Top" Width="367"/>
</Grid>
It seems to me that on the ToolWindowPane, there is a Grid, and on the Grid another Grid, and on that Grid, a Tabcontrol. From this post it seems that some controls do not resize. So would that mean that the TabControl can't resize even if it is on a Grid?
When the user resizes the ToolWindowPane, the contents does not resize.
How can I achieve correct resizing in this situation?
The base of the problem is the explicit Width and Height values are being set and preventing the controls from fitting into their container.
To make the page salable across resolutions/devices, you must ensure that there are no fixed width/height property specified; instead we can use them in percentage (%) which will make the controls scale based on available viewport. Try replacing all the fixed height & width properties for your control with percentages.
if for some reasons the controls are getting squeezed you can try providing minHeight & minWidth to the control as documented here https://www.w3schools.com/cssref/pr_dim_min-height.asp
Having some trouble getting my head around all the DP's i've recreated a very simple version of of my problem to try and sort out what the issue is. Alas, im still stumped..
I Have a custom userControl, and am attempting to set the properties of a textblock through the page that is instantiating that control. At the moment, in this version below, as a means of teaching myself im only trying to access a property from code behind.
The reason I wish to set custom text properties etc. is because I wish to have multiple versions of the control on the page with custom behaviour/text etc.
Here is my code behind.
public partial class FeedbackCtrl : UserControl
{
public bool IsFlagSet
{
get { return (bool)GetValue(IsFlagSetProperty); }
set { SetValue(IsFlagSetProperty, value); }
}
public static readonly DependencyProperty IsFlagSetProperty =
DependencyProperty.Register("IsFlagSet", typeof(bool), typeof(FeedbackCtrl), new PropertyMetadata(false));
public FeedbackCtrl()
{
InitializeComponent();
this.DataContext = this;
}
}
And my XAML..
<UserControl x:Class="Pipeline_General.Custom_Controls.FeedbackCtrl" x:Name="ThisCtrl"
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"
d:DesignHeight="300" d:DesignWidth="300">
<Grid>
<Expander HorizontalAlignment="Stretch" >
<Expander.Header Name="Header">
<Grid HorizontalAlignment="Stretch" Width="NaN">
<Border Background="Transparent" HorizontalAlignment="Stretch" BorderBrush="gray" BorderThickness="0,0,0,1"
Width="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Expander}}, Path=ActualWidth}">
<TextBlock Foreground="#FFFF72D2" Text="{Binding Path=IsFlagSet}">
</TextBlock>
</Border>
</Grid>
</Expander.Header>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="30" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<ScrollViewer Grid.Row="1">
<StackPanel Orientation="Vertical" VerticalAlignment="Top" Margin="5"/>
</ScrollViewer>
</Grid>
</Expander>
</Grid>
I have the following XAML where I have two combobox controls with the same ItemsScource. I used the IsSynchronizedWithCurrentItem=False to attempt to get them to act individually. But still changing one changes the other.
XAML
<Page x:Class="HaMmeR.FantasyFootball.TradeEvalPage"
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="300" d:DesignWidth="300"
Title="TradeEvalPage">
<Grid x:Name="masterPanel">
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition/>
</Grid.RowDefinitions>
<DockPanel Grid.Row="0" Grid.Column="0" Style="{DynamicResource dockLsLabel}">
<Label x:Name="teamName1Lbl" Content="Team Name" Style="{DynamicResource lsLabel}" />
<!--IsSynchronizedWithCurrentItem=False Treat datasource as individual-->
<ComboBox x:Name="teamName1Cmb" Margin="2" DockPanel.Dock="Right"
ItemsSource="{Binding Path=FantasyTeams}"
IsSynchronizedWithCurrentItem="False"
DisplayMemberPath="TeamName"
SelectionChanged="teamName1Cmb_SelectionChanged"
SelectedValuePath="TeamName" SelectedValue="{Binding Path=TeamName}"/>
</DockPanel>
<DockPanel Grid.Row="0" Grid.Column="1" Style="{DynamicResource dockLsLabel}">
<Label x:Name="teamName2Lbl" Content="Team Name" Style="{DynamicResource lsLabel}" />
<ComboBox x:Name="teamName2Cmb" Margin="2" DockPanel.Dock="Right"
ItemsSource="{Binding Path=FantasyTeams}"
IsSynchronizedWithCurrentItem="False"
DisplayMemberPath="TeamName"
SelectionChanged="teamName2Cmb_SelectionChanged"
SelectedValuePath="TeamName" SelectedValue="{Binding Path=TeamName}"/>
</DockPanel>
</Grid>
</Page>
.cs File
public partial class TradeEvalPage : Page
{
private FantasyLeague league;
public TradeEvalPage(FantasyLeague League)
{
InitializeComponent();
league = League;
//FantasyTeamCollection team1Source = new FantasyTeamCollection(league.FantasyTeams.ToList<FantasyTeam>());
//FantasyTeamCollection team2Source = new FantasyTeamCollection(league.FantasyTeams.ToList<FantasyTeam>());
//teamName1Cmb.DataContext = team1Source;
//teamName2Cmb.DataContext = team2Source;
masterPanel.DataContext = league;
//mainContent.Text = string.Format("You clicked Trade Evalution of {0}", league.LeagueName);
}
}
I can't figure out what I'm doing wrong. Any help would be appreciated.
I think because you Bind the selectedValue to the TeamName.
SelectedValue="{Binding Path=TeamName}"
If you remove the bind, they probably work. I think whats happen here is, when you change the selection in one combobox, the value of the new selected item is written in the current items-name. So it looks that the first combobox does the same, but if you open it, you'll see that value twice.
I have the following main.xaml and usercontrol.
I need to place several times the user control on the 2nd row, 2nd column of the grid, By using visual studio it wont allow to drag and drop the user control, so I suppose I have to do it by code, I just dont know how
MainPage.xaml
<Grid HorizontalAlignment="Left" Height="768" VerticalAlignment="Top" Width="1366" x:Name="grid" Background="Black">
<Grid.RowDefinitions>
<RowDefinition Height="150"/>
<RowDefinition/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition Width="250"/>
</Grid.ColumnDefinitions>
<Border BorderBrush="White" BorderThickness="3" Grid.Column="1" Background="Red" CornerRadius="30"/>
<TextBlock x:Name="txtCountry" Grid.Column="1" TextWrapping="Wrap" FontSize="36" HorizontalAlignment="Center" VerticalAlignment="Center"/>
<TextBlock x:Name="txtTime" Grid.Row="1" TextWrapping="Wrap" FontSize="180" HorizontalAlignment="Center" VerticalAlignment="Center"/>
</Grid>
Usercontrol
<UserControl
x:Class="AlarmPro.TimeOnCity"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:AlarmPro"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="150"
d:DesignWidth="250">
<Grid Background="Black">
<Grid.RowDefinitions>
<RowDefinition Height="30"/>
<RowDefinition/>
</Grid.RowDefinitions>
<Border BorderBrush="#FFDE6A6A" BorderThickness="1" Grid.Row="0" Grid.Column="0" Background="#FFDC4646">
<TextBlock TextWrapping="Wrap" Text="TextBlock" HorizontalAlignment="Center" VerticalAlignment="Center" FontSize="16"/>
</Border>
<Border BorderBrush="Black" BorderThickness="1" Grid.Row="1" Background="#FFAE4F00">
<TextBlock TextWrapping="Wrap" Text="TextBlock" HorizontalAlignment="Center" VerticalAlignment="Center" FontSize="36"/>
</Border>
</Grid>
</UserControl>
Do you mean like this?
<my:UserControlName Grid.Column="2" Grid.Row="2" ... />
<my: in this case is the alias for the CLR namespace the UserControl resides in. It is defined at the top of your XAML, inside the <Window> or <UserControl> tag depending on context.
For example,
<Window ...
xmlns:my="clr-namespace:AssemblyName"
...
/>
MainPage.Xaml
<Page
x:Class="UserControlExample.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:UserControlExample"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Grid x:Name="MainContent" Background="Azure" >
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<ScrollViewer Grid.Row="1" HorizontalScrollBarVisibility="Hidden"
VerticalScrollBarVisibility="Hidden">
<local:UserControl1 x:Name="MyHelloWorldUserControl" Grid.Row="1" />
</ScrollViewer>
</Grid>
</Page>
UserControl1.xaml
<UserControl
x:Class="UserControlExample.UserControl1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:UserControlExample"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="300"
d:DesignWidth="400">
<Grid Background="Bisque">
<StackPanel>
<StackPanel Orientation="Horizontal" Height="81">
<TextBlock Text="Your Name is" Foreground="Blue" FontSize="30" Margin="0,0,0,10"/>
<TextBox x:Name="Input" Background="White" Width="225" />
</StackPanel>
<Button Content="Click Me" Foreground="Brown" FontSize="30" Click="Button_Click"/>
<TextBlock x:Name="Output" FontSize="100"/>
</StackPanel>
</Grid>
</UserControl>
MainPage.xaml, I am binding a login UserControl
by using the namespace : xmlns:UC="clr-namespace:Test.Views" , since I have my usercontrol in Folder named "Views".
<ScrollViewer>
<UC:Login BtnLoginClick="Login_BtnLoginClick"/>
</ScrollViewer>
Login.cs
public partial class Login : UserControl {
public event EventHandler BtnLoginClick;
public Login()
{
InitializeComponent();
}
private void btnLogin_Click(object sender, RoutedEventArgs e)
{
string userName = txtUserName.Text;
string userPassword = txtUserPassword.Password.Trim();
if (userName != null && userName != string.Empty && userPassword != null && userPassword != string.Empty)
{
if (this.BtnLoginClick != null)
{
this.BtnLoginClick(this, e);
}
}
else
{
MessageBox.Show("Invalid username or password");
}
}
}
Finally, dont forgot to use the event handler in MainPage.xaml to capture the button clicked event from Login Usercontrol to do other actions.
MainPage.xaml
<UC:Login BtnLoginClick="Login_BtnLoginClick"/>
Here "BtnLoginClick" its an event Handler defined in the Login.xaml[User Control].
Create new event for this "BtnLoginClick" event as i created "Login_BtnLoginClick".
MainPage.cs
private void Login_BtnLoginClick(object sender, EventArgs e)
{
Messagebox.Show("Event captured successfully");
////Here you can add your stuffs...
}
For UWP, in UserControl.xaml, find the local namespace xmlns:local notation: xmlns:local="using:ProjectName.Folder" at the top (by convention, C# namespaces are named the same way as the folder that contains them, so folder also means namespace).
In MainPage.xaml, add a reference to this namespace. The reference prefix can be any name desired: for example, CustomPrefix, as in xmlns:CustomPrefix="using:ProjectName.Folder". Then, anywhere in MainPage.xaml, display the control by prefixing its name with <CustomPrefix:...>.
UserControl.xaml
<UserControl
xmlns:local="using:ProjectName.Folder">
MainPage.xaml
<Page
xmlns:CustomPrefix="using:ProjectName.Folder">
<CustomPrefix:UserControl />
</Page>
The project needs to be built to discard XAML errors in Visual Studio, otherwise the design view remains blank and the XAML has green squiggles.