今天用到了需要再wpf的用户控件中将枚举值以参数的方式传递到ViewModel,搜索了很多资料都是将枚举绑定到列表或者Combox的数据源中,经过多次尝试可以将枚举中的单个值以参数的方式传递到ViewModel了,进行一下记录。
1、在页面中添加枚举所在的命名空间以及系统枚举类型的命名空间
xmlns:cusEnum="clr-namespace:MessageReminderClient.Model.CommonModel"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
2、添加界面资源
<UserControl.Resources>
<ObjectDataProvider x:Key="DataEnum" MethodName="GetValues" ObjectType="{x:Type
sys:Enum}">
<ObjectDataProvider.MethodParameters>
<x:Type TypeName="cusEnum:MessageTypeEnum"></x:Type>
</ObjectDataProvider.MethodParameters>
</ObjectDataProvider>
</UserControl.Resources>
其中sys:Enum的命名空间在第一步骤中已经添加(即xmlns:sys),DataEnum为资源取的名字,TypeName就是枚举类型的名称。
3、将枚举值绑定到CommandParameter中,这样就能在ViewModel的ClassificationChangedCommand命令参数中获取到该枚举的值
<RadioButton Style="{StaticResource ChooseButtonStyle}"
IsChecked="True"
Command="{Binding ClassificationChangedCommand}"
CommandParameter="{x:Static
cusEnum:MessageTypeEnum.UnRead}"
Content="未读">
</RadioButton>
4、ViewModel中的代码如下:
①声明命令
ClassificationChangedCommand = new BaseCommond();
ClassificationChangedCommand.DoExecute = new Action<object>(ClassificationChanged);
ClassificationChangedCommand.DoCanExecute = new Func<object, bool>((o) => true);
②命令实现,其中pObjParam就是传进来的枚举值,直接在switch中跟case进行判断即可
private void ClassificationChanged(object pObjParam)
{
if (SelectedBenchNode == null)
{
return;
}
string roomName = SelectedBenchNode.roomname;
ParamsInfo paramsInfo = CreateDefaultParam(roomName);
switch (pObjParam)
{
case MessageTypeEnum.UnRead:
paramsInfo = CreateDefaultParam(roomName, -1, 0, SerachText ?? "");
SelectedMessageType = MessageTypeEnum.UnRead;
break;