【发布时间】:2015-07-27 14:59:40
【问题描述】:
我定义了一个枚举,我的目的是在 ListBox 中向用户显示四个选项(无、左、中和右)。此 ListBox 将允许进行多项选择。单击保存命令后,我必须将选择传递给 ViewModel,在该视图模型中我将聚合选择并将其传递给 WCF 服务。
枚举:
[DataContract]
[Flags]
public enum Locations
{
None = 0,
[EnumMember]
Left = 1,
[EnumMember]
Center = 2,
[EnumMember]
Right = 4,
[EnumMember]
LeftCenter = Left | Center,
[EnumMember]
LeftRight = Left | Right,
[EnumMember]
CenterRight = Center | Right,
[EnumMember]
All = Left | Center | Right
}
XAML:
<Button Command="{Binding SaveCommand}"
CommandParameter="{Binding SelectedItems, ElementName=lbLocations}" />
<ListBox x:Name="lbLocations" SelectionMode="Multiple">
<ListBoxItem Content="{x:Static m:Subsections.None}" />
<ListBoxItem Content="{x:Static m:Subsections.Left}" />
<ListBoxItem Content="{x:Static m:Subsections.Center}" />
<ListBoxItem Content="{x:Static m:Subsections.Right}" />
</ListBox>
视图模型:
public ICommand SaveCommand
{
get
{
if (_saveCommand == null)
_saveCommand = new RelayCommand<IList>(x => Save(x));
return _saveCommand;
}
}
private void Save(IList locations)
{
try
{
// ToList() produces InvalidCastException.
var collection = locations.Cast<Locations>().ToList();
// Do WCF stuff, display success, etc.
}
catch (Exception ex)
{
_dialogService.Show(ex.Message, "Error");
}
}
我已成功地将选择作为 IList 传递回我的 ViewModel,但我很难将其转换回我的枚举。有没有更好的方法我忽略了,这可以工作吗?看来我快到了。
【问题讨论】: