Reputation: 23
I created a sample custom control. It generates a dll after i build the project. Following is the code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace textbtn
{
public class CustomControl1 : Control
{
static CustomControl1()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(CustomControl1), new FrameworkPropertyMetadata(typeof(CustomControl1)));
}
}
}
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:textbtn">
<Style TargetType="{x:Type local:CustomControl1}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:CustomControl1}">
<Border Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
<TextBlock Text="This is a Test" Foreground="Aqua" Background="AntiqueWhite"/>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
I am including this dll in another WPF application and wants to show this custom control when user clicks a button in the application. How do i do that ?
Following is the code in my WPF application.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace TestCustomControls
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void button1_Click(object sender, RoutedEventArgs e)
{
textbtn.CustomControl1 cc = new textbtn.CustomControl1();
}
}
}
Upvotes: 0
Views: 552
Reputation: 61369
That strongly depends on what you mean by show. To just add it to the display:
AddChild(cc);
This adds it to the windows children group. This will probably blow up, since a window can only have one child. If you have a root grid called "ContentGrid", then it would be:
ContentGrid.Children.Add(cc);
The problem with both these approaches is that you don't control the position. You can set margin properties etc. to fix that of course. If your custom control were to inherit from Window (instead of control), you could do a show dialog if you want a dialog box:
cc.ShowDialog();
Of course, better than all these approaches would be to just show it in XAML instead of modifying the UI in code-behind :)
Upvotes: 1