[英]How to create an ItemTemplate for a ComboBox programmatically?
我想以編程方式為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。
通過代碼生成模板是通過工廠(即FrameworkElementFactory)完成的。 您可以通過FrameworkElement類型生成工廠,並通過工廠上的方法設置綁定等。
在msdn上給出了類似的問題和一個簡單的示例: http : //social.msdn.microsoft.com/Forums/en-US/wpf/thread/f230804d-fc0f-4321-a61e-69a2c890b28d/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.