我想以编程方式为 ComboBox
创建一个 ItemTemplate
(如主题所述)。
目前我在 XAML 中有一个 ItemTemplate
:
<Style x:Key="ComboBox_EntityCreation_GroupSelect_Style" TargetType="{x:Type ComboBox}">
<Setter Property="ItemTemplate">
<Setter.Value>
<DataTemplate>
<TextBlock>
<TextBlock.Text>
<MultiBinding StringFormat="{}{0} {1} Mitglied(er)">
<Binding Path="Name"/>
<Binding Path="MemberCount"/>
</MultiBinding>
</TextBlock.Text>
</TextBlock>
</DataTemplate>
</Setter.Value>
</Setter>
</Style>
由于我对 XAML 的厌恶,我希望在没有 XAML 的情况下获得结果。
这有可能吗?
最佳答案
我刚刚即时转换了它。请检查它是否有效。
Style style = new Style(typeof(ComboBox));
var d = new DataTemplate();
MultiBinding mb = new MultiBinding();
mb.StringFormat = "{0} {1} Mitglied(er)";
mb.Bindings.Add(new Binding("Name"));
mb.Bindings.Add(new Binding("MemberCount"));
FrameworkElementFactory textElement = new FrameworkElementFactory(typeof(TextBlock));
textElement.SetBinding(TextBlock.TextProperty, mb);
d.VisualTree = textElement;
style.Setters.Add(new Setter(ComboBox.ItemTemplateProperty, d));
this.Resources.Add("ComboBox_EntityCreation_GroupSelect_Style", style);
您可以使用 FrameworkElementFactory 将 DataTemplate 分配给它的 VisualTree。
关于c# - 如何以编程方式为 ComboBox 创建 ItemTemplate?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12662541/