How to position relative to a child element within another control in XAML - xaml

In a UWP app, I have a custom UserControl with some child controls (text boxes, labels, etc.). I have a Page that includes that UserControl as a child element. Now, I want to place a button below that UserControl and align it with one of the control's child text boxes using a RelativePanel. I can't figure out a way to access the child element.
For example, I have a custom control:
<UserControl
x:Class="Sandbox.FooControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:Sandbox"
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>
<TextBox
x:Name="TheTextBoxIWantToAlignWith"
x:FieldModifier="public"/>
</Grid>
And now I want to align with "TheTextBoxIWantToAlignWith":
<UserControl
x:Class="Sandbox.FooParentControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:Sandbox"
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">
<RelativePanel>
<local:FooControl
x:Name="Foo"
RelativePanel.AlignTopWithPanel="True"
RelativePanel.AlignHorizontalCenterWithPanel="True"/>
<Button
RelativePanel.Below="Foo"
RelativePanel.AlignLeftWith="Foo.TheTextBoxIWantToAlignWith"/> <!-- This doesn't work -->
</RelativePanel>
Obviously this doesn't work ("RelativePanel error: The name 'Foo.TheTextBoxIWantToAlignWith' does not exist in the current context."). I tried:
Setting the FieldModifier to public on the child TextBox
Exposing the TextBox as a public property in code-behind
Exposing the TextBox as a DependencyProperty in code-behind
I really want to avoid flattening out the UserControl into the parent page because it can be reused elsewhere. Is there any way to do this?

I ended up working around the issue with code-behind, similar to Lindsay's suggestion. I hooked into the LayoutUpdated event, which calculated and set the margin. Something like this:
private void AlignButton()
{
var transform = Foo.TheTextBoxIWantToAlignWith.TransformToVisual(RootPanel);
var textBoxRightEdge = transform .TransformPoint(new Point()).X + Foo.TheTextBoxIWantToAlignWith.ActualWidth;
var rightMargin = RootPanel.ActualWidth - textBoxRightEdge;
if (Math.Abs(TheButtonIWantToAlign.Margin.Right - rightMargin) >= 1)
TheButtonIWantToAlign.Margin = new Thickness(0, 0, rightMargin, 0);
}

Related

How do you add varible in UWP xaml?

I want to add a variable to my xaml.
My xaml looks like this
<Page
x:Class="UwpTest.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:UwpTest"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:system="using:System"
mc:Ignorable="d"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Page.Resources>
<system:String x:Key="var1">1.2</system:String>
</Page.Resources>
<Grid>
</Grid>
</Page>
When run, I get runtime error.
Microsoft.UI.Xaml.Markup.ReflectionHelperException
HResult=0x80131500
Message=Error in reflection helper. Please add '<PropertyGroup><EnableTypeInfoReflection>false</EnableTypeInfoReflection></PropertyGroup>' to your project file.. Created Xaml type 'String' has a different name than requested type 'System.String'
Source=Windows
StackTrace:
at Windows.UI.Xaml.Application.LoadComponent(Object component, Uri resourceLocator, ComponentResourceLocation componentResourceLocation)
at UwpTest.MainPage.InitializeComponent() in D:\Dev\UwpTest\UwpTest\obj\x86\Debug\MainPage.g.i.cs:line 33
at UwpTest.MainPage..ctor() in D:\Dev\UwpTest\UwpTest\MainPage.xaml.cs:line 27
I want to add a variable to my xaml
You could add x:String into resource as variable for example
<x:String x:Key="var1">Hello</x:String>
For more please refer to XAML intrinsic data types

RegisterPropertyChangedCallback works only the first time

This is a follow up question related to a control that needs to intercept when common control properties changes (Inherit UserControl and hooking up to basic property events).
When any base property changes (foregound, font style, size...), I need to invalidate the canvas and redraw the content.
I've ended up with calling this method inside the UserControl constructor:
RegisterPropertyChangedCallback(DependencyProperty dp, DependencyPropertyChangedCallback callback);
For example:
RegisterPropertyChangedCallback(ForegroundProperty, OnPropertyChanged);
RegisterPropertyChangedCallback(FontFamilyProperty, OnPropertyChanged);
RegisterPropertyChangedCallback(FontSizeProperty, OnPropertyChanged);
Inside OnPropertyChanged I proceed to rewire some property and invalidate the canvas in order to update the picture.
The control is inside a DataTemplate referenced by a Pivot (PivotHeaderTemplate). The default Foreground is the unselected status (semi-transparent SystemControlForegroundBaseMediumBrush) and should get the default "white" when selected (SystemControlHighlightAltBaseHighBrush).
The control Foreground property is applied by a template, and according to the live tree it's updating, but OnPropertyChanges is called only the first time.
For example, the Pivot has 2 views: the first one starts selected and is white, and the second is unselected and is "grayish".
If I change the selection, the view changes, the Foreground property changes accordingly on both controls but OnPropertyChanges is not called, and my canvas doesn't change (because the invalidation logic is inside that method).
[UPDATE: as a workaround, I used the event LayoutUpdated to check what changed.]
For a test project, create a new UWP XAML project a new MyCanvas UserControl.
MyCanvas.xaml:
<UserControl x:Class="InheritControlProperty.Controls.MyCanvas"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:InheritControlProperty.Controls"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Canvas x:Name="content" Width="50" Height="50"/>
</UserControl>
MyCanvas.xaml.cs
using System;
using Windows.UI;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media;
namespace InheritControlProperty.Controls
{
public sealed partial class MyCanvas : UserControl
{
private Color Value
{
get { return (Foreground as SolidColorBrush)?.Color ?? Colors.Black; }
}
public MyCanvas()
{
InitializeComponent();
RegisterPropertyChangedCallback(ForegroundProperty, OnPropertyChanged);
}
private void OnPropertyChanged(DependencyObject sender, DependencyProperty dp)
{
content.Background = new SolidColorBrush(Value);
//Logic for more complex canvas management here
}
}
}
MainPage.xaml
<Page x:Class="InheritControlProperty.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:InheritControlProperty"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:cntr="using:InheritControlProperty.Controls"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Page.Resources>
<DataTemplate x:Key="NameTemplate">
<Grid BorderBrush="Orange" BorderThickness="2">
<cntr:MyCanvas Width="100" Height="50"/>
<!-- Try using Foreground="Red" -->
</Grid>
</DataTemplate>
</Page.Resources>
<Pivot Margin="20" HeaderTemplate="{StaticResource NameTemplate}">
<PivotItem>Item 1</PivotItem>
<PivotItem>Item 2</PivotItem>
</Pivot>
</Page>

Binding Visibility to DataContext

I have a value converter that converts null to Visibility.Collapsed. Now I try to use it in a user control so that the whole control would collapse when it's DateContext is null
The control looks like this:
<UserControl x:Class="PhoneApp.Controls.Header"
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"
Visibility="{Binding Converter={StaticResource ToVisibility}}"
d:DesignHeight="150" d:DesignWidth="480"> <-- some body here -->
And it is used like this
<my:Header DataContext="{Binding SectionHeader}"/>
Where SectionHeader is a view model property.
I hava a similar control where I don't bind DataContext but some custom DP and the collapsing there works fine. However, in this one, the value converter seems to be called only when the SectionHeader != null. When it is null, the control is rendered with empty children.
I thought about not using DataContext here but the control is much cleaner with it.
Why binding to DataContext doesn't work? What do you suggest?
In this case, when DataContext is null, binding will use value specified in TargetNullValue property. So simply set TargetNullValue=Collapsed and you're good to go :
Visibility="{Binding TargetNullValue=Collapsed}"
Reference : [How to Set TargetNullValue to Visibility.Collapsed in Binding]

XAML designer does not see C++/CX classes

Windows Store project in C++/CX. I've placed an instance of the custom C++ class on a XAML page. I've marked it with a namespace. The project builds. Yet the design surface does not display the control, claims it's not present in the assembly. The XAML goes like this:
<UserControl
x:Class="MyApp.Foo"
xmlns:local="using:MyApp"
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"
d:DesignHeight="300"
d:DesignWidth="400" Loaded="OnLoaded">
...
<local:MyControl x:Name="Bar" HorizontalAlignment="Left" VerticalAlignment="Top"/>
The MyControl class is declared in code like this:
[Windows::Foundation::Metadata::WebHostHidden]
public ref class MyControl sealed : Windows::UI::Xaml::Controls::Canvas
{
...
};
It has a public default contructor with no parameters. What's wrong here, please?

How to check which instance of child control is used in silverlight

I have two usercontrols : ParentUserControl.xaml and ChildUserControl.xaml
ParentUserControl:
<UserControl x:Class="DemoSilverlight.ParentUserControl"
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:DemoSilverlight"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="400" xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk"
Loaded="UserControl_Loaded">
<Grid x:Name="LayoutRoot" Background="White">
<sdk:TabControl x:Name="tabControlHeatMapEditor" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" SelectionChanged="tabControlHeatMapEditor_SelectionChanged" Height="510" FontFamily="Verdana" FontSize="12">
<sdk:TabItem Header="Original Heat Map" x:Name="tabItemOriginalHeatMap">
<Local:ChildUserControl x:Name="chartControlOriginal"/>
</sdk:TabItem>
<sdk:TabItem Header="Revised Heat Map" x:Name="tabItemRevisedHeatMap">
<Local:ChildUserControl x:Name="chartControlRevised"/>
</sdk:TabItem>
<sdk:TabItem Header="Compare Original/Revised" x:Name="tabItemCompareOrgRev">
<!--<Local:ChildUserControl x:Name="chartControlCompare"/>-->
</sdk:TabItem>
</sdk:TabControl>
</Grid>
</UserControl>
Inside the ChildUserControl control I have a button control. In the code behind page of the
ChildUserControl.xaml.cs, I want to know which instance of the ChildUserControl is used and based on that I want to access the button within the ChildUserControl in order to make it disabled.
Can anyone help me to resolve this problem
Thanks & Regards,
Santosh Kumar Patro
Have a enum in ChildUserControl. Based on TabItem Selection set the enum property and further based on your condition you can either enable or disable the button.