Hi
I want to create a custom control which would only contain RadioButtons. I imagine it being used as follows:
<RadioButtonHolder Orientation="Horizontal">
<RadioButton>RadioButton 1</RadioButton>
<RadioButton>RadioButton 2</RadioButton>
<RadioButton>RadioButton 3</RadioButton>
<RadioButton> ...</RadioButton>
</RadioButtonHolder>
Currently, I have created a custom control which partially does this. However it seems to keep an ongoing collection of the RadioButtons. And it would add this collection of RadioButtons to the last control initialized. Does anyone know why this may be? Any help is much appreciated.
Edit:
I kind of figured out what was happening in this. It seems that when the object is initialized it will create a list of RadioButtons
, which contains all the RadioButtons and then it would attach it to all the RadioButtonHolder
controls in the window as children. And the last control gets to display the items.
However I'm not sure how to prevent this and only localize the content to each control. So that if I wrote:
<RadioButtonHolder Name="RBH1">
<RadioButton Name="RB1">RB 1</RadioButton>
<RadioButton Name="RB2">RB 2</RadioButton>
</RadioButtonHolder>
<RadioButtonHolder Name="RBH2">
<RadioButton Name="RB3">RB 3</RadioButton>
<RadioButton Name="RB4">RB 4</RadioButton>
</RadioButtonHolder>
RB1
& RB2
will be displayed in RBH1
and RB3
& RB4
will be displayed as children in RBH2
.
My code is as follows:
CustomControl.cs
using System.Collections.Generic;
using System.Windows;
using Sytem.Windows.Controls;
using System.Windows.Markup;
namespace RandomControl
{
[ContentProperty("Children")]
public class CustomControl1 : Control
{
public static DependencyProperty ChildrenProperty =
DependencyProperty.Register("Children", typeof(List<RadioButton>),
typeof(CustomControl1),new PropertyMetadata(new List<RadioButton>()));
public List<RadioButton> Children
{
get { return (List<RadioButton>)GetValue(ChildrenProperty); }
set { SetValue(ChildrenProperty, value); }
}
static CustomControl1()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(CustomControl1),
new FrameworkPropertyMetadata(typeof(CustomControl1)));
}
}
}
Generic.xaml
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:RandomControl">
<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}">
<ItemsControl ItemsSource="{TemplateBinding Children}"
Background="{TemplateBinding Background}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel></StackPanel>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>