将ComboBox的SelectedValue分配给viewmodel wpf的字符串属性

时间:2016-12-08 10:04:23

标签: c# wpf mvvm combobox prism

所以我有非常简单的combobox包含值列表。我应该将selectedvalue绑定到viewmodel属性并将其存储在DB中。以下是我目前的做法:

SampleViewModel.cs

public class SampleViewModel: BindableBase
{
    public SampleViewModel()
    {
        MyDetails = new ObservableCollection<DetailItems>(){
            new DetailItems{Name="Detail1"},
            new DetailItems{Name = "Detail2"},
            new DetailItems{Name= "Detail3"},
            new DetailItems{Name="Detail4"}
        };
    }

    private ObservableCollection<DetailItems> _myDetails;
    private string _myDetail;

    public ObservableCollection<DetailItems> MyDetails { get { return _myDetails; } set { SetProperty(ref _myDetails, value); } }
    public string MyDetail { get { return _myDetail; } set { SetProperty(ref _myDetail, value); } }
}

public class DetailItems: BindableBase
{
    private string _name;
    public string Name { get { return _name; } set { SetProperty(ref _name, value); } }
}

ComboBox中的View如下

<ComboBox x:Name="cbDetails" 
                  ItemsSource="{Binding MyDetails}" 
                  DisplayMemberPath="Name" 
                  SelectedValuePath="{Binding Path=Name}" 
                  SelectedValue="{Binding MyDetail}"/>

但每当我在后端获取数据时,字符串MyDetail将有一个DetailItems实例转换为string。任何人都可以告诉我如何更改此选项以将适当的值绑定到MyDetail

2 个答案:

答案 0 :(得分:1)

原因很简单: UITabBarItem.appearance().titlePositionAdjustment = UIOffsetMake(0.0, 100.0) 需要对象属性的路径,而不是绑定(就像SelectedValuePath那样)。所以修复就是:

DisplayMemberPath

答案 1 :(得分:0)

显然, SelectedValue 始终只保留当前选定的项目。因此,您必须将类型从字符串更改为 DetailItems ,如下所示,

private DetailItems_myDetail;
 public DetailItems MyDetail { get { return _myDetail; } set { SetProperty(ref _myDetail, value); } }
}

如果您希望所选名称调用 MyDetail.Name ,则会返回您的字符串