c# - 如何以编程方式为 ComboBox 创建 ItemTemplate?

标签 c# wpf xaml

我想以编程方式为 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/

相关文章:

c# - DataTrigger 绑定(bind)到 UserControl 依赖属性

c# - 限制 SharePoint 计时器作业的执行时间?

c# - Process.RedirectStandardOutput 不起作用

WPF 设置子窗口标题

c# - 数据绑定(bind)到不同 UserControl 中的 ObservableCollection - 如何保留当前选择?

wpf - 在 XAML 中指定命名颜色的透明度级别

c# - 使用 Azure 移动服务的 Azure Active Directory 身份验证失败

C# 正则表达式部分字符串匹配

c# - 根据 RadioButton 更改绑定(bind)

c# - 使用样式化的单元格更改在DataGrid中突出显示所选行的方式