UWP How to create user control that hosts content? - c#

I am getting really frustrated in trying to achieve a very trivial thing (or at least, something what I would expect should be trivial...)
I have a requirement where a toggle button should be customized, for which I need to make a user control which hosts the toggle button, and host the content which is described in that user control. I made a small mini app to demonstrate the "requirement".
<local:MyUserControl1>
<TextBlock>Just an example</TextBlock>
</local:MyUserControl1>
The MyUserControl1 looks as follows:
<UserControl
x:Class="App2.MyUserControl1"
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" Name="Bla" d:DesignHeight="300" d:DesignWidth="400">
<UserControl.Resources>
<Style TargetType="ToggleButton">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate>
<Grid>
<Ellipse Width="300" Height="300" Fill="Blue"/>
<ContentPresenter Content="{Binding ElementName=Bla, Path=MainContent}"/>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</UserControl.Resources>
<ToggleButton/>
</UserControl>
Code behind:
public static DependencyProperty MainContentProperty = DependencyProperty.Register(
"MainContent",
typeof(object),
typeof(MyUserControl1),
null);
public object MainContent
{
get => GetValue(MainContentProperty);
set => SetValue(MainContentProperty, value);
}
When I run the app, the text is shown, but the style / togglebutton is ignored / not applied / whatever.
The visual tree confirms that I do something wrong:
I have viewed many many other related SO Q&As, but I still have no idea how to get this working the way I want.

You code should be working, except that there are no lines shown where ContentPropertyAttribute should be. Could you make sure that MyUserControl1 has it's content property identified and see if that helps.
[ContentProperty(Name = "MainContent")]
public sealed partial class MyUserControl1 : UserControl
...
Update
There is full code below that was tested with Win 10 Pro 1803, build 17134, NETCore 6.2.2.
Note that you can define control template either in UserControl.Resources or external resources to separate it from the "main" UI layout or keep it in ToggleButton.Template for a few less lines of XAML.
UserControlWithContent.xaml
<UserControl
x:Class="SmallTests2018.UserControlWithContent"
x:Name="Self"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<ToggleButton>
<ToggleButton.Template>
<ControlTemplate>
<Grid>
<Ellipse Width="300" Height="300" Fill="Blue"/>
<ContentPresenter
HorizontalAlignment="Center"
VerticalAlignment="Center"
Content="{Binding MainContent, ElementName=Self, FallbackValue='{}{ content }'}" />
</Grid>
</ControlTemplate>
</ToggleButton.Template>
</ToggleButton>
</UserControl>
UserControlWithContent.xaml.cs
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Markup;
namespace SmallTests2018
{
[ContentProperty(Name = "MainContent")]
public sealed partial class UserControlWithContent : UserControl
{
public UserControlWithContent()
{
this.InitializeComponent();
}
public static DependencyProperty MainContentProperty =
DependencyProperty.Register("MainContent", typeof(object), typeof(UserControlWithContent), null);
public object MainContent
{
get => GetValue(MainContentProperty);
set => SetValue(MainContentProperty, value);
}
}
}
UserControlWithContentPage.xaml
<Page
x:Class="SmallTests2018.UserControlWithContentPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:SmallTests2018"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Viewbox>
<local:UserControlWithContent>
<TextBlock FontSize="32" Foreground="Yellow">Just an example</TextBlock>
</local:UserControlWithContent>
</Viewbox>
</Page>
Page XAML designer screenshot

Related

making button .xaml public to another class in wpf controller

I have this button from Main window.xaml need to call it from another class
i made it just like first answer
How to make a control in XAML public in order to be seen in other classes
<Window x:Class="USD.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="450" Width="525">
<Button ToolTip="Answer Call" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="107,82,0,0" x:Name="answerCall" Click="answerCall_Click" Visibility="Hidden" x:FieldModifier="public">
<StackPanel Orientation="Horizontal" >
<Image Width="35" Height="35" Source="Images/unnamed.png" RenderTransformOrigin="4.075,0.607">
</Image>
</StackPanel>
<Button.Template>
<ControlTemplate TargetType="Button">
<Grid>
<ContentPresenter HorizontalAlignment="Center"
VerticalAlignment="Center"/>
</Grid>
</ControlTemplate>
</Button.Template>
</Button>
but when i checked it from any .cs class just like that
MainWindow.answerCall.Visibility.Visible;
give errors
i fixed it by this in C# code
DispatcherPriority.Background,
new Action(() => ((MainWindow)System.Windows.Application.Current.MainWindow).answerCall.Visibility = Visibility.Visible));
If you use a controller/viewmodel, you shouldn't have any code behind, instead of that, you should work with bindable properties and commands, implementing INotifyPropertyChanged interface, in some base class if you want.

Databinding to nested UserControl

I would like to bind a property from a nested UserControl to my MainWindow.
I'm already using a similar structure for other things but this is a bit different:
-MainWindow
--Ribbon
---RibbonButton <-- the button I would like to disable
--/Ribbon
--UserControl1 - not directly the control I want bind to
---UserControl2 - nested user control, sitting inside the above one
----TextBox <-- Bind the RibbonButton to the Text property. Disable the button when TextBox empty
---/UserControl2
--/UserControl
-/MainWindow
So, the usual combination of Elementname and Path doesn't work here obviously. Is DataContext the way to go here? The UserControls are in separate files and so is the MainWindow. Or should I do this in code-behind?
Some of the code I'm having there:
MainWindow
<RibbonWindow.Resources>
<BooleanToVisibilityConverter x:Key="BoolToVis"/>
</RibbonWindow.Resources>
...
<RibbonGroup Header="Import">
<RibbonButton x:Name="mplImpFromForum" Label="From forum" FontSize="12" LargeImageSource="Icons/General/Icon8_download_72px.png" Click="mplImpFromForum_Click"/>
<RibbonButton x:Name="mplImpManual" Label="Manual import" SmallImageSource="Icons/General/Icon8_whole_hand_32px.png"}>
<RibbonButton.Style>
<Style>
<Style.Triggers>
<DataTrigger Binding="{Binding ElementName=frmLogin, Path=}"
// here lies my problem
</Style.Triggers>
</Style>
</RibbonButton.Style>
</RibbonButton>
</RibbonGroup>
</RibbonTab>
</Ribbon>
<Viewbox Grid.Row="1" Panel.ZIndex="1" MaxHeight="200" MaxWidth="200">
<local:frmLogin x:Name="frmLogin" Loaded="frmLogin_Loaded" Grid.Row="1"/>
</Viewbox>
<local:frmMPLMain x:Name="frmMPLMain" Grid.Row="1"/> // "Source UserControl, "parent
to the real target.
The first nested UserControl
<UserControl x:Class="Fever_Tool_WPF.frmMPLMain"
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:Fever_Tool_WPF"
mc:Ignorable="d"
x:Name="MPLRoot"
d:DesignHeight="500" d:DesignWidth="1000">
...
<local:frmMPLImp x:Name="frmMPLImp" Grid.Column="2" Grid.ColumnSpan="4" Grid.RowSpan="6"/>
// The second UserControl, this one contains the TextBox I want to take as a source
<DataGrid HeadersVisibility="None" Grid.RowSpan="3" Grid.ColumnSpan="2"></DataGrid>
</Grid>
The second UserControl
<UserControl x:Class="Fever_Tool_WPF.frmMPLImp"
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:Fever_Tool_WPF"
mc:Ignorable="d"
d:DesignHeight="500" d:DesignWidth="1000">
<UserControl.Resources>
<Style x:Key="uiMPLImpBaseStyle" TargetType="{x:Type FrameworkElement}">
<Setter Property="Margin" Value="5"/>
</Style>
</UserControl.Resources>
...
<TextBox x:Name="txtMPLImport" Style="{StaticResource uiMPLImpBaseStyle}" Grid.Row="2" Grid.ColumnSpan="4"/>
// This is the textbox I would like to check.
...
</Grid>

WPF, XAML: CustomControl like TextBox with caption

My attempt to create a CustomControl like a TextBox with variable caption.
I try to learn create CustomControl and my exceptation is that my CustomControl (I called it TextBoxCustomControl) has every properties and methods of TextBox and also has new property Caption.
I hope that is right, that my TextBoxCustomControl is inherited from TextBox and not from Control.
TextBoxCustomControl.cs
namespace CustomControlProject
{
public class TextBoxCustomControl : TextBox
{
public static readonly DependencyProperty CaptionProperty = DependencyProperty.Register("Caption", typeof(string), typeof(TextBoxCustomControl), new FrameworkPropertyMetadata(String.Empty));
public string Caption
{
get { return (string)GetValue(CaptionProperty); }
set { SetValue(CaptionProperty, value); }
}
static TextBoxCustomControl()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(TextBoxCustomControl), new FrameworkPropertyMetadata(typeof(TextBoxCustomControl)));
}
}
}
Themes\Generic.xaml (specific design for TextBoxCustomControl) -- there is the TextBox called innerTextBox
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:CustomControlProject">
<Style x:Name="CustomStyle" TargetType="local:TextBoxCustomControl" BasedOn="{StaticResource {x:Type TextBox}}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:TextBoxCustomControl}">
<WrapPanel Orientation="Vertical">
<TextBox x:Name="innerTextBox" />
<Label Content="{TemplateBinding Caption}" />
</WrapPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
In MainWindow.xaml I use my TextBoxCustomControl and specific some properties for it.
<Window x:Class="CustomControlProject.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:CustomControlProject"
Title="MainWindow" Height="350" Width="525">
<WrapPanel>
<local:TextBoxCustomControl Width="287" Background="Yellow" Caption="Fill the nickname, please." />
</WrapPanel>
</Window>
My expectation is that innerTextBox inside my TextBoxCustomControl inherit all properties (such like background, width, etc.), but that is not happened. What I do wrong?
First off, there's a difference between a CustomControl, inheriting from a Control, and an UserControl composed out of several Controls.
The Style you're applying is overriding all the TextBox's properties. When you set a Template, you need to use TemplateBinding for all the properties that you want to bind against later. If not, they will be no longer accessible from the outside.
For what you're trying to achieve, you can skip the Style and change XAML to
<Window x:Class="CustomControlProject.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:CustomControlProject"
Title="MainWindow" Height="350" Width="525">
<StackPanel>
<local:TextBoxCustomControl
x:Name="CustomBox"
Width="287" Background="Yellow"
Caption="Fill the nickname, please." />
<Label
Content="{Binding ElementName=CustomBox, Path=Caption}" />
</StackPanel>
</Window>
To make it all-in-one, you'd need to build a UserControl.
First of all, what you are making is a composite control. So, inheriting it from TextBox doesn't make any sense. Inheriting from TextBox would make sense if you are improving a normal TextBox with additional capabilities.
Your thinking that whatever you set at your custom control level will be inherited by child controls is wrong. If you want to do that, use TemplateBinding for individual properties. Eg; <TextBox x:Name="innerTextBox" Width="{TemplateBinding Width}"/> .
Note : Some properties (FontSize, FontFamily) are propagated anutomatically without any extra work.
What you are trying to make is already present as <HeaderedContentControl/> . You can study its source code here or using ILSpy.
Sample :
<HeaderedContentControl>
<HeaderedContentControl.Header>
<Border>
<TextBlock Text="Name please !"/>
</Border>
</HeaderedContentControl.Header>
<HeaderedContentControl.Content>
<TextBox />
</HeaderedContentControl.Content>
</HeaderedContentControl>

How to set a property in a trigger (WPF)

I have a user control that has a text box and a button.
I want to disable the text box using trigger ( I know how to do this via code)
The XAML is as follow:
<UserControl x:Class="MyProject.UserControl1"
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:l="clr-namespace:MyProject"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<UserControl.Resources>
<Style TargetType="l:UserControl1" >
<Style.Triggers>
<Trigger Property="l:UserControl1.IsEditing" Value="True">
<Setter Property="IsEnabled" Value="False"></Setter>
</Trigger>
</Style.Triggers>
</Style>
</UserControl.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<Button Content="Button" HorizontalAlignment="Left" x:Name="button1" VerticalAlignment="Top" Width="75" Grid.Row="0" Click="button1_Click" />
<TextBox Height="23" HorizontalAlignment="Left" x:Name="textBox1" VerticalAlignment="Top" Width="120" Grid.Row="1"/>
</Grid>
</UserControl>
The code is:
using System;
using System.Windows;
using System.Windows.Controls;
namespace MyProject
{
/// <summary>
/// Interaction logic for UserControl1.xaml
/// </summary>
public partial class UserControl1 : UserControl
{
public static readonly DependencyProperty IsEditingProperty = DependencyProperty.Register(
"IsEditing", typeof(Boolean), typeof(UserControl), new PropertyMetadata(false));
public Boolean IsEditing
{
get { return (Boolean)GetValue(IsEditingProperty); }
set { SetValue(IsEditingProperty, value); }
}
public UserControl1()
{
InitializeComponent();
}
private void button1_Click(object sender, RoutedEventArgs e)
{
IsEditing = !IsEditing;
}
}
}
But this setup disable both TextBox and button. How can I only disable the button? If I have several Textbox and I want only some of them are disabled, what is the best option? If I have several different UIElements (such as textbox, calandar, datagrid and .. and I want to disable all of them using one triger, what should I do?
Try moving the style down to your grid, and set the TargetName to textBox1. See the answer to this question for an example: Triggers Based on Properties from DataContext
Btw, you should be able to bind the value of IsEditing directly to textBox1.IsEnabled (warning: coding in-place, so code may not work as-is)
<Button IsEnabled="{Binding Path=IsEditing RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl1}}} />
Set the TargetName of the Setter to the name of the button.
best option is group them and and then disable in one go.
in your code, you havent specified the x:Key for your style, if you dont specify the key, it tries to use it as default style for all controls type of UserControl1. and then you can attach that style to your child controls in your UserControl1:
for Key:
<Style x:Key="styleDefault" TargetType="Control">
attach style to your child controls:
<Button Style="{StaticResource styleDefault}"></Button>
I think the problem here is that you are using a EventTrigger, it is the only trigger that can be set directly on a style, not using template. AFAIK if you use this kind of trigger you can only set properties of the object that fired the event.

TwoWay Binding with UserControl

I am trying to set twoway binding on a UserControl that I have created.
When I use the control in Xaml is set the DataContext like so...
<uc:MyUserControl DataContext="{Binding Path=MyObject, Mode=TwoWay}" />
My user control is defined as the following....
<UserControl x:Class="SilverlightApplication1.XText"
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">
<Grid x:Name="LayoutRoot" Background="White">
<TextBox x:Name="Text" Text="{Binding}"/>
</Grid>
</UserControl>
The data is displayed correctly, however if I make I change I wanted it to update with TwoWay binding.
I have tried this below, but it errors at runtime since no Path is defined.
<Grid x:Name="LayoutRoot" Background="White">
<TextBox x:Name="Text" Text="{Binding Mode=TwoWay}"/>
</Grid>
</UserControl>
Any ideas on how to get the control inside the usercontrol to twoway bind to the DataContext?
While your above (self-answered) answer seems to fix the problem, I can't help but think this is a problem domain issue. I have a hard time thinking why you'd want to bind directly like that in the first place, especially since it gives you less control over what happens with the data.
Take the following:
<UserControl
x:Class="SilverlightApplication1.XText"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
x:Name="UserControl"
d:DesignHeight="300"
d:DesignWidth="400">
<Grid x:Name="LayoutRoot" Background="White">
<TextBox x:Name="Text" Text="{Binding Path=Value, ElementName=UserControl, Mode=TwoWay}"/>
</Grid>
</UserControl>
Then in the codebehind:
public partial class XText
{
public static DependencyProperty ValueProperty =
DependencyProperty.Register(
"Value",
typeof(string),
typeof(XText),
new FrameworkPropertyMetadata(null)
);
public string Value
{
get { return ((string)(base.GetValue(XText.ValueProperty))); }
set { base.SetValue(XText.ValueProperty, value); }
}
...
}
Then, when you're ready to use it:
<uc:XText Value="{Binding Path=MyObject, Mode=TwoWay}" />
Yes, it's more code, but it gives you much more control over what happens with Value inside of your UserControl, and makes working with this code much much simpler in the future.
Thoughts?
-Doug
EDIT: fixed a couple typos.
I have found a solution that doesn't require you to give a name to the base control.
When I defined a name for the base UserControl it was creating issues for me when I was adding multiple instances to my Grid, since they were defined as the same name.
This is a combination of my first answer and Doug's answer.
Note the UserControl lacks the name property and the TextBox has no Binding declared in the XAML
XAML
<UserControl
x:Class="SilverlightApplication1.XText"
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">
<Grid x:Name="LayoutRoot" Background="White">
<TextBox x:Name="MyText"/>
</Grid>
</UserControl>
CodeBehind
public partial class XText
{
public XText()
{
InitializeComponent();
MyText.SetBinding(TextBox.TextProperty, new Binding()
{
Source = this,
Path = new PropertyPath("Value"),
Mode = BindingMode.TwoWay
});
}
public static DependencyProperty ValueProperty =
DependencyProperty.Register(
"Value",
typeof(string),
typeof(XText),
new PropertyMetadata(null)
);
public string Value
{
get { return ((string)(GetValue(ValueProperty))); }
set { SetValue(ValueProperty, value); }
}
...
}
When you are ready to use it do the following
<uc:XText Value="{Binding Path=MyObject, Mode=TwoWay}" />
Ok I think I have come up with a way to get this to work....
First I set a public property in my UserControl's code behind...
public Binding BindingValue
{
set { this.MyTextBox.SetBinding(TextBox.TextProperty, value); }
}
Then in XAML
<uc:MyUserControl BindingValue="{Binding Path=MyObject, Mode=TwoWay}" />

Categories

Resources