【发布时间】:2009-07-24 10:27:19
【问题描述】:
我想创建一个只包含 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 中显示为子项。
我的代码如下:
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>
【问题讨论】:
标签: wpf-controls custom-controls radio-button