5
A User Control can be used for various purposes, but I would specifically like to know a simple example of how to create a User Control any that returns any value.
For example a Numericupdown:
Created from this code XAML:
<UserControl x:Class="TCC_2.Templates.NumericUpDown1"
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:TCC_2.Templates"
mc:Ignorable="d"
d:DesignHeight="40" d:DesignWidth="200">
<Grid x:Name="Grid1" MouseWheel="Grid_MouseWheel">
<Grid.RowDefinitions>
<RowDefinition Height="0.5*"/>
<RowDefinition Height="0.5*" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="0.8*"/>
<ColumnDefinition Width="0.2*"/>
</Grid.ColumnDefinitions>
<TextBox x:Name="txtValue" DataObject.Pasting="TextBoxPasting" Grid.Column="0" BorderThickness="0" VerticalContentAlignment="Center" Text="0" FontSize="18" Grid.RowSpan="2" Foreground="#444" PreviewTextInput="txtValue_PreviewTextInput" TextChanged="txtValue_TextChanged" />
<Button x:Name="btnIncrease" Grid.Column="1" Grid.Row="0" Foreground="#444" FontSize="10" VerticalContentAlignment="Center" Background="#ccc" Content="▲" BorderThickness="0" Cursor="Hand" Click="btnIncrease_Click" />
<Button x:Name="btnDecrease" Grid.Column="1" Grid.Row="1" Foreground="DarkGray" FontSize="10" VerticalContentAlignment="Top" Content="▼" BorderThickness="0" Cursor="Hand" Height="20" Click="btnDecrease_Click" />
</Grid>
</UserControl>
With these main methods in C#:
private void btnIncrease_Click(object sender, RoutedEventArgs e)
{
value++;
txtValue.Text = value.ToString();
btnDecrease.Foreground = new System.Windows.Media.SolidColorBrush(color);
btnDecrease.IsEnabled = true;
}
private void btnDecrease_Click(object sender, RoutedEventArgs e)
{
if (value > 0)
{
if (value == 1)
{
btnDecrease.Foreground = Brushes.DarkGray;
btnDecrease.IsEnabled = false;
}
value--;
txtValue.Text = value.ToString();
}
}
The point is... let’s say I put this Control on one page XAML... How do I get the text from inside the Textbox txtValue ?
Calling in the page code for example the "Numericupdown1.Text"
I’ve tried using this Binding on the property Text textbox:
Text="{Binding RelativeSource={RelativeSource AncestorType=UserControl},Path=Text}"
But on the page when calling this property it does not exist.
So how do I get that value ?