此代码在我的应用程序中变得越来越普遍:
<StackPanel Orientation="Vertical">
<Label Content="_ComboBox Caption"
Target="comboBox"
Margin="0"
Padding="5,5,5,1" />
<ComboBox x:Name="comboBox"
Width="72"
Margin="5,0,5,5"
Padding="5,1,5,5"
SelectedItem="{Binding ComboSelectedItem}"
ItemsSource="{Binding ComboSourceList}" />
</StackPanel>
它呈现给我一个带标题的组合框。
我想让我成为一个自定义控件,它是一个组合框,它公开标签的内容,然后设置其他属性。可以这样使用的东西:
<Controls:CaptionedComboBox x:Name="comboBox"
Width="72"
LabelContent="_ComboBox Caption"
SelectedItem="{Binding ComboSelectedItem}"
ItemsSource="{Binding ComboSourceList}" />
但是,我研究了制作自定义控件并且需要令人生畏的样式。
有没有办法利用我上面的内容并最终做这样的事情?
<StackPanel Orientation="Vertical">
<Label Content="{Binding TemplateLabelContent}"
Target="{Binding ControlName}"
Margin="0"
Padding="5,5,5,1" />
<InheritedComboBoxStuff/>
</StackPanel>
我知道那行不通。但我的观点是,我必须重新设计整个 ComboBox 的样式只是为了在其上方添加一个标签,这似乎很愚蠢。
最佳答案
你可以为那个做一个模板
<ControlTemplate x:Key="ComboWithHeader" TargetType="ContentControl">
<StackPanel Orientation="Vertical">
<Label Margin="0"
Content="{Binding ComboBoxHeader}"
DataContext="{TemplateBinding DataContext}"
Padding="5,5,5,1"
Target="comboBox" />
<ComboBox x:Name="comboBox"
Width="72"
Margin="5,0,5,5"
DataContext="{TemplateBinding DataContext}"
ItemsSource="{Binding ComboSourceList}"
Padding="5,1,5,5"
SelectedItem="{Binding ComboSelectedItem}" />
</StackPanel>
</ControlTemplate>
然后每当你想使用带有标题的组合时,只需使用
<ContentControl Template="{StaticResource ComboWithHeader}" DataContext="{Binding ComboBoxViewModel}" />
关于c# - 向 WPF ComboBox 控件添加标签的简单方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12590449/