将ListBox(或Telerik RadListPicker)绑定到Enum

时间:2011-12-22 20:42:34

标签: telerik mvvm-light windows-phone-7

我有一个枚举:

public enum UnitOfMeasure
{
    Meters,
    Kilometers,
    Yards,
    Miles,
    Time
}

我希望将它绑定到ListBox(实际上是Telerik RadListPicker,但它的工作方式相同):

<telerikInput:RadListPicker
    Header="Measure work in:"
    ItemsSource="{Binding WorkUnitOfMeasure}"
    HeaderStyle="{StaticResource HeaderStyle}"
    x:Name="workUnitsListPicker"
    Margin="18">
</telerikInput:RadListPicker>

我的视图模型:

/// <summary>
/// The <see cref="WorkUnitOfMeasure" /> property's name.
/// </summary>
public const string WorkUnitOfMeasurePropertyName = "WorkUnitOfMeasure";

private ObservableCollection<Enum<UnitOfMeasure>> _workUnitOfMeasure;
/// <summary>
/// Gets the WorkUnitOfMeasure property.
/// Changes to that property's value raise the PropertyChanged event. 
/// This property's value is broadcasted by the Messenger's default instance when it changes.
/// </summary>
public ObservableCollection<Enum<UnitOfMeasure>> WorkUnitOfMeasure
{
    get
    {
        return _workUnitOfMeasure;
    }
    set
    {
        if (_workUnitOfMeasure == value)
        {
            return;
        }
        var oldValue = _workUnitOfMeasure;
        _workUnitOfMeasure = value;
         RaisePropertyChanged(WorkUnitOfMeasurePropertyName);
    }
}

在我的构造函数中,我尝试过类似的变体:

WorkUnitOfMeasure = new ObservableCollection<Enum<UnitOfMeasure>>();

我似乎无法将列表框绑定到Enum。我知道我错过了一些简单的东西,但我无法弄明白。

2 个答案:

答案 0 :(得分:1)

我认为应该是

ObservableCollection<UnitOfMeasure>

不是

ObservableCollection<Enum<UnitOfMeasure>

如果不是你看到了什么错误?

答案 1 :(得分:0)

如果要将单个枚举项绑定到列表框:

以下代码可以帮助您:

 List<string> newList = new List<string>();
        for (int i = 0; i <= (int)UnitOfMeasure.Time; i++)
            newList.Add(Enum.GetName(typeof(UnitOfMeasure), i));
        SampleList.ItemsSource = newList;