gpt4 book ai didi

.net - 从ListBox SelectedItems属性检索枚举

转载 作者:行者123 更新时间:2023-12-03 10:17:36 28 4
gpt4 key购买 nike

我定义了一个Enum,我的意图是在列表框中向用户显示四个选项(无,左,中和右)。该列表框将允许多个选择。单击save命令时,我必须将选择传递给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>

ViewModel:
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,但是我很难将其强制返回给我的枚举。有没有我忽略的更好的方法,这行得通吗?好像我快到了。

最佳答案

尝试遍历转换列表并将该值聚合到一个变量中,如下所示:

private void Save(IList locations)
{
try
{
Locations location = Locations.None;

foreach (Locations value in locations.Cast<Locations>())
{
location |= value;
}

// Do WCF stuff, display success, etc.
}
catch (Exception ex)
{
_dialogService.Show(ex.Message, "Error");
}
}

关于.net - 从ListBox SelectedItems属性检索枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31656523/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com