所以我在列表中有一个自定义类。我似乎无法获取要绑定(bind)的列表和组合框。该列表应显示自定义类的所有名称值。我想用代码来做到这一点。非常感谢任何帮助(一如既往!)。
最好给出一些我认为的代码片段。
类(class):
public class Asset : IComparable<Asset>
{
...
public String name { get { return _name; } set { _name = value; } }
...
}
列表和我尝试的绑定(bind),是不是 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"/>
最佳答案
您可以尝试的是在 xaml set ItemsSource="{Binding}"
和代码后面的 set
cboAsset1.DataContext = assetsForCbos;
我个人更喜欢在 Xaml 中进行所有绑定(bind),因此如果需要更改,我只需查看 xaml。
编辑:如果您想显示名称属性,而不是 Namespace.Asset,您可以执行以下操作之一
- 重写 Asset 类中的 ToString 以返回 Assets 名称。
注意:这不会改变,因此如果 Assets 对象中的名称发生变化, View 中也不会更新。 创建一个 DataTemplate,其中包含 StackPanel(我选择的轻量级布局容器)和 StackPanel 内绑定(bind)到 name 属性的 TextBlock。当您在代码中创建组合框时,您可以这样做。
// 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;
关于c# - WPF 将 List<custom> 绑定(bind)到 C# 代码中的组合框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3564449/