【发布时间】:2019-03-01 07:25:03
【问题描述】:
我正在尝试创建一个自定义 ItemsControl,它显示 RadioButtons 或 Checkboxes 并自动将样式应用于这些项目。
这就是我现在拥有的:
自定义项目控件:
public class LabelContainer : ItemsControl
{
public string Label
{
get { return (String)GetValue(LabelProperty); }
set { SetValue(LabelProperty, value); }
}
public static readonly DependencyProperty LabelProperty =
DependencyProperty.Register("Label", typeof(string),
typeof(LabelContainer), new PropertyMetadata(""));
}
样式:
<ItemsPanelTemplate x:Key="ItemsPanelTemplate">
<StackPanel Orientation="Horizontal">
<StackPanel.Resources>
<Style TargetType="{x:Type RadioButton}" >
<Setter Property="Margin" Value="0,0,8,0"/>
</Style>
</StackPanel.Resources>
</StackPanel>
</ItemsPanelTemplate>
<Style TargetType="local:LabelContainer">
<Setter Property="ItemsPanel" Value="{StaticResource ItemsPanelTemplate}"></Setter>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="local:LabelContainer">
<StackPanel>
<TextBlock FontWeight="Medium" Margin="0,0,7,6" Text="{TemplateBinding Label}"/>
<ItemsPresenter>
<ItemsPresenter.Resources>
<Style TargetType="{x:Type RadioButton}">
<Setter Property="Margin" Value="0,0,8,0"/>
</Style>
<Style TargetType="{x:Type CheckBox}">
<Setter Property="Margin" Value="0,0,8,0"/>
</Style>
</ItemsPresenter.Resources>
</ItemsPresenter>
</StackPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
我是这样使用它的:
<local:LabelContainer Label="RadioButtons:">
<RadioButton>Nr 1</RadioButton>
<RadioButton>Nr 2</RadioButton>
</local:LabelContainer>
一切正常,除了对单个项目进行样式设置。在这种情况下,我试图为单选按钮添加边距。我知道我可以手动为每个项目添加边距,但我试图避免这种情况。
我尝试将样式放入主样式的 ItemsPresenter.Resources 中,并尝试将其放入 ItemsPanelTemplate 的 StackPanel.Resources 中。这两个选项都不起作用,样式未应用。
任何想法为什么这不起作用?
【问题讨论】:
标签: c# wpf xaml itemscontrol itemspresenter