所以我在列表中有一个自定义类。我似乎无法获得列表和组合框来绑定。该列表应显示customclass的所有名称值。我想在代码中执行此操作。最值得赞赏的任何帮助(一如既往!)。
我认为最好是提供一些代码片段。
班级:
public class Asset : IComparable<Asset>
{
...
public String name { get { return _name; } set { _name = value; } }
...
}
列表和我的尝试绑定,是不是ComboBox.ItemBindingGroupProperty是错的?
List<Asset> assetsForCbos = new List<Asset>();
assetsForCbos.Add(new Asset("example asset"));
Binding bindingAssetChoice = new Binding();
bindingAssetChoice.Source = assetsForCbos;
bindingAssetChoice.Path = new PropertyPath("name");
bindingAssetChoice.Mode = BindingMode.OneWay;
cboAsset1.SetBinding(ComboBox.ItemBindingGroupProperty, bindingAssetChoice);
在XAML中我有
<ComboBox Height="23"
ItemsSource="{Binding}"
HorizontalAlignment="Left"
Margin="10,8,0,0"
Name="cboAsset1"
VerticalAlignment="Top"
Width="228"
IsReadOnly="True"
SelectedIndex="0"/>
答案 0 :(得分:3)
您可以尝试使用xaml set ItemsSource="{Binding}"
和set
cboAsset1.DataContext = assetsForCbos;
我个人喜欢在Xaml中进行所有绑定,所以如果需要进行更改,我只需要查看xaml。
编辑:如果您想显示name属性,而不是Namespace.Asset,则可以执行以下操作之一
创建一个DataTemplate,其中包含StackPanel(我选择的轻量级布局容器)和StackPanel中绑定到name属性的TextBlock。正如你在代码中创建ComboBox一样,你可以这样做。
// Create Data Template
DataTemplate itemsTemplate = new DataTemplate();
itemsTemplate.DataType = typeof (Asset);
// Set up stack panel
FrameworkElementFactory sp = new FrameworkElementFactory(typeof (StackPanel));
sp.Name = "comboStackpanelFactory";
sp.SetValue(StackPanel.OrientationProperty, Orientation.Horizontal);
// Set up textblock
FrameworkElementFactory assetNameText = new FrameworkElementFactory(typeof (TextBlock));
assetNameText.SetBinding(TextBlock.TextProperty, new Binding("name"));
sp.AppendChild(assetNameText);
// Add Stack panel to data template
itemsTemplate.VisualTree = sp;
// Set the ItemsTemplate on the combo box to the new data tempalte
comboBox.ItemTemplate = itemsTemplate;