2015-05-04 33 views
-1

我有一個與Enum綁定的組合框,My Enum有模型級別所需的None或NA值,但這些值與UI級別的用戶無關。我不想顯示它們到user.I也不想使用一個單獨的枚舉的視圖模型和view.So我做了一個標記擴展將從項目source.Here刪除無或NA是我code`從項目源中刪除項目僅用於UI

public sealed class EnumBindingHelper : MarkupExtension 
{ 

    private readonly Type _enumType; 

    public EnumBindingHelper(Type enumType) 
    { 
     _enumType = enumType; 

    } 

    public override object ProvideValue(IServiceProvider serviceProvider) 
    { 

     var arr= Enum.GetValues(_enumType); 

     var list = (from object item in arr select item.ToString()).ToList(); 

     list.RemoveAll(x => x.Equals("None") || x.Equals("NA") || x.Equals("NONE") || x.Equals("Na")); 

     return list; 
    } 
} 

我的看法綁定

<ComboBox ItemsSource="{helpers:EnumBindingHelper {x:Type MyEnum}}" SelectedItem="{Binding SelectedValue,Mode=TwoWay}"/> 

它在UI中的工作正常,我沒有看到NA和組合框中沒有值,但選擇我在啓動應用程序時,UI中的d項總是空的。

MY枚舉是在我的視圖模型代碼

MyEnum 
{ 
    value1=0, 
    value2=1, 
    value3=2, 
    None=4 

} 

蔭也設置的SelectedValue =值。 任何人都可以解釋爲什麼發生這種情況,我該如何解決這個問題。我希望正常行爲,如選定的項目應該是綁定或第一個項目,如果選定的項目爲空。

+0

這是一個參考的問題。如果你想從視圖模型中設置選定的值,你可以從ItemSource獲得你想要的值。否則它將始終爲空 – Guerudo

+0

我能想到的解決方法..但我會嘗試設置issynchronizedwithcurrentitem =「True」 https://msdn.microsoft.com/en-us/library/system.windows.controls.primitives.selector .issynchronizedwithcurrentitem%28V = vs.110%29.aspx –

回答

0

的的MarkupExtension應該返回過濾枚舉值,而不是字符串:

private static readonly string[] exclude = 
    new string[] { "None", "NONE", "Na", "NA" }; 

public override object ProvideValue(IServiceProvider serviceProvider) 
{ 
    return Enum.GetValues(_enumType).Cast<object>() 
     .Where(e => !exclude.Contains(e.ToString())).ToList(); 
}