我想创建一个只包含 RadioButtons 的自定义控件。我想它被如下使用:
<RadioButtonHolder Orientation="Horizontal">
<RadioButton>RadioButton 1</RadioButton>
<RadioButton>RadioButton 2</RadioButton>
<RadioButton>RadioButton 3</RadioButton>
<RadioButton> ...</RadioButton>
</RadioButtonHolder>
目前,我创建了一个部分执行此操作的自定义控件。然而,它似乎保留了 RadioButtons 的持续集合。它会将这个 RadioButtons 集合添加到最后一个初始化的控件中。有谁知道为什么会这样?任何帮助深表感谢。
编辑:
我有点弄清楚这里面发生了什么。似乎当对象被初始化时,它会创建一个RadioButtons
包含所有 RadioButtons 的列表,然后它将它RadioButtonHolder
作为子项附加到窗口中的所有控件。最后一个控件开始显示项目。
但是我不确定如何防止这种情况,只将内容本地化到每个控件。所以如果我写:
<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
将显示在 中RBH1
,RB3
&RB4
将显示为RBH2
.
我的代码如下:
自定义控件.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)));
}
}
}
通用的.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>