我在这篇SO帖子之后在WPF中构建了一个多列组合框:WPF ComboBox Multiple Columns
(请原谅大量的代码示例;))
Combobox XAML
<ComboBox Name="cmbProductTypeMulti" IsEditable="False" Margin="0,2,10,2" MaxDropDownHeight="250"
Text="{Binding Path=AcctData.ProductType}" ItemsSource="{Binding Path=ProductTypeSelection}">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Margin="2" Text="{Binding Path=ProductType}"/>
</DataTemplate>
</ComboBox.ItemTemplate>
<ComboBox.ItemContainerStyle>
<Style TargetType="ComboBoxItem" BasedOn="{StaticResource ComboBoxItemStyle}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate>
<Border Name="ComboBoxItemBorder" BorderThickness="1">
<Grid Name="ComboBoxItemGrid" TextElement.Foreground="Black">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="60"/>
<ColumnDefinition Width="150"/>
</Grid.ColumnDefinitions>
<TextBlock Margin="5,3" Grid.Column="0" Text="{Binding ProductType}"/>
<TextBlock Margin="5,3" Grid.Column="1" Text="{Binding Description}" FontSize="10"/>
</Grid>
</Border>
<ControlTemplate.Triggers>
<!--- snip --->
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ComboBox.ItemContainerStyle>
</ComboBox>
ViewModel代码段
Public Class AccountsViewModel
Inherits ViewModelBase
//The view model's main Poco
Dim _AcctData As Models.Account
//The multicolumn combobox's Poco
Dim _ProductTypeSelection As IEnumerable(Of Models.ProductType)
Public Property AcctData As Account
Get
Return _AcctData
End Get
Set(value As Account)
MyBase.Set(Of Account)(Function() AcctData, _AcctData, value)
End Set
End Property
Public Property ProductTypeSelection As IEnumerable(Of ProductType)
Get
Return _ProductTypeSelection
End Get
Set(value As IEnumerable(Of ProductType))
MyBase.Set(Of IEnumerable(Of ProductType))(Function() ProductTypeSelection, _ProductTypeSelection, value)
End Set
End Property
...
End Class
查看Poco片段
Public Class Account
Inherits ObservableObject
Private _ProductType As String
Public Property ProductType As String
Get
Return _ProductType
End Get
Set(value As String)
MyBase.Set(Of String)(Function() ProductType, _ProductType, value)
End Set
End Property
...
End Class
Combobox的Poco
Public Class ProductType
Inherits ObservableObject
Private _ProductType As String
Private _Description As String
Public Property ProductType As String
...
End Property
Public Property Description As String
...
End Property
...
End Class
首先,当我将帐户加载到视图模型的AcctData.ProductType中时,该值不会显示在多列组合框中。我有一个常规组合框绑定到相同的值,正确显示AcctData.ProductType初始值。
其次,当我从多列组合框中选择一个项目时,常规组合框会丢失其选定的项目并变为空白。当我进入调试并查看vm的AcctData.ProductType时,我发现它已被分配了ProductType poco的ToString值。
所以看起来多列组合框试图使用整个Poco来绑定。我怎样才能使用Poco中的属性作为其绑定值?
由于
答案 0 :(得分:1)
如果您要从viewmodel的构造函数调用ProductTypeSelection setter来初始化数据,那么第一个问题可能会得到解决,因为目前它没有设置en因此不会提高属性event,目前你的绑定只知道初始数据是默认的空值
第二个问题可能是因为xaml是在你定义的controltemplate上的datatemplate,如果你把控件模板中的xaml放在datatemplate里面,可能会解决这个问题
答案 1 :(得分:1)
我设法找到一个hacky工作。
由于多列组合框是使用Poco的ToString()值绑定的,我只是修改了ToString()以返回ProductType属性,这是我想要绑定的属性!现在,多列组合框的行为应该如此 - 即使它在技术上绑定到错误的属性。