我有这个愚蠢的问题。我从视图模型类的属性类型BindableCollection绑定到ComboBox控件的ItemSource属性。
来自视图模型类的代码:
public class SpiritUser
{
public string Nick { get; set; }
public string Password { get; set; }
}
public BindableCollection<SpiritUser> SpiritUsers
{
get { return _spiritUsers; }
set
{
_spiritUsers = value;
NotifyOfPropertyChange(() => SpiritUsers);
}
}
//constructor of view model class
public LogOnViewModel()
{
SpiritUsers = new BindableCollection<SpiritUser>
{
new SpiritUser
{
Nick = "Spirit_1",
Password = "slniecko1"
},
new SpiritUser
{
Nick = "Spirit_2",
Password = "slniecko1"
}
};
}
在视图中我有这个:
Style on comboBox:
<Style x:Key="LogOnView_NickComboBox" TargetType="{x:Type ComboBox}">
<Setter Property="ItemTemplate">
<Setter.Value>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"></ColumnDefinition>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="*"></RowDefinition>
</Grid.RowDefinitions>
<Label Content="{Binding Path=Nick}" Grid.Column="0" Grid.Row="0"/>
</Grid>
</DataTemplate>
</Setter.Value>
</Setter>
<Setter Property="Height" Value="25"/>
<Setter Property="FontSize" Value="13"/>
<Setter Property="Margin" Value="10,4,10,4"/>
<Setter Property="VerticalAlignment" Value="Center"/>
</Style>
ComboBox控件:
<ComboBox ItemsSource="{Binding Path=SpiritUsers, Mode=OneWay,UpdateSourceTrigger=PropertyChanged}"
Style="{StaticResource LogOnView_NickComboBox}"
SelectedValuePath="Nick"
Text="{Binding Path=Nick, Mode=OneWayToSource, UpdateSourceTrigger=PropertyChanged}"
SelectedValue="{Binding Path=Nick, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
IsEditable="True"/>
如果我选择一些comboBox项目,我会看到 Spirit.Models.SpiritUser 而不是项目文字。
如果将comboBox属性IsEditable设置为true,则会出现问题。
如何解决这个问题,我需要在comboBox上使用视图模型的bind属性,但我还需要comboBox可编辑并将用户输入绑定到视图模型中的属性。
答案 0 :(得分:4)
如果是可编辑的组合框,请使用DisplayMemberPath属性而不是ItemTemplate来指定要显示的绑定对象的属性:
<ComboBox ItemsSource="{Binding Path=SpiritUsers, Mode=OneWay,UpdateSourceTrigger=PropertyChanged}"
Style="{StaticResource LogOnView_NickComboBox}"
DisplayMemberPath="Nick"
SelectedValuePath="Nick"
Text="{Binding Path=CurrentUserNick, Mode=OneWayToSource, UpdateSourceTrigger=PropertyChanged}"
IsEditable="True"/>
如果你仍想使用ItemTemplate,那么你可以通过TextSearch.TextPath附加属性指定你应该在文本框中显示你的对象的属性:
<ComboBox ItemsSource="{Binding Path=SpiritUsers, Mode=OneWay,UpdateSourceTrigger=PropertyChanged}"
Style="{StaticResource LogOnView_NickComboBox}"
SelectedValuePath="Nick"
TextSearch.TextPath="Nick"
Text="{Binding Path=CurrentUserNick, Mode=OneWayToSource, UpdateSourceTrigger=PropertyChanged}"
IsEditable="True"/>