WPF将列表<custom>绑定到C#代码中的组合框?</custom>

时间:2010-08-25 09:28:16

标签: c# wpf binding

所以我在列表中有一个自定义类。我似乎无法获得列表和组合框来绑定。该列表应显示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"/>

1 个答案:

答案 0 :(得分:3)

您可以尝试使用xaml set ItemsSource="{Binding}"和set

后面的代码
cboAsset1.DataContext = assetsForCbos;

我个人喜欢在Xaml中进行所有绑定,所以如果需要进行更改,我只需要查看xaml。

编辑:如果您想显示name属性,而不是Namespace.Asset,则可以执行以下操作之一

  1. 覆盖Asset类中的ToString以返回资产名称 注意:这不会改变,因此如果名称在Asset对象中更改,则不会在视图中更新。
  2. 创建一个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;