如何使用C#代码构建DataTemplate?

我正在尝试为winform互操作构建下拉列表,并且正在代码中创建下拉列表。但是,我在根据我指定的DataTemplate绑定数据时遇到问题。


我想念什么?


drpCreditCardNumberWpf = new ComboBox();  

DataTemplate cardLayout = new DataTemplate {DataType = typeof (CreditCardPayment)};   

StackPanel sp = new StackPanel

{

    Orientation = System.Windows.Controls.Orientation.Vertical

};   


TextBlock cardHolder = new TextBlock {ToolTip = "Card Holder Name"};

cardHolder.SetBinding(TextBlock.TextProperty, "BillToName");

sp.Children.Add(cardHolder);


TextBlock cardNumber = new TextBlock {ToolTip = "Credit Card Number"};

cardNumber.SetBinding(TextBlock.TextProperty, "SafeNumber");

sp.Children.Add(cardNumber);


TextBlock notes = new TextBlock {ToolTip = "Notes"};

notes.SetBinding(TextBlock.TextProperty, "Notes");

sp.Children.Add(notes);


cardLayout.Resources.Add(sp, null);


drpCreditCardNumberWpf.ItemTemplate = cardLayout;


小怪兽爱吃肉
浏览 562回答 3
3回答

繁星淼淼

好吧,实际上我们还有另一种方法,如果您不喜欢这些FrameworkElementFactory东西,您将真的很喜欢。而且我认为它只是对自然代码进行了微小的更改,即声明a UserControl并将您的控件放入其中,然后仅使用一个FrameworkElementFactory调用UserControl。简单的演示代码(在F#中):let buildView()=StackPanel()//Build it with natural codetype MyView()=inherit UserControl(Content=buildView())let factory=FrameworkElementFactory(typeof<MyView>)let template=DataTemplate(VisualTree=factory)let list=ItemsControl(ItemsSource=makeData(),ItemTemplate=template)
打开App,查看更多内容
随时随地看视频慕课网APP