2016-09-02 47 views
0

我已經開發了C#UWP中枚舉類型屬性的子類組合框控件。UWP subclassed組合框控件在C#中枚舉 - 顯示

它很好用!幾乎所有的時間(...類型)。

當枚舉的類型是Windows.UI.Text.FontStyle時出現問題。

項目選擇仍然有效的權利,但它顯示是不是的ToString()值,但Windows.Foundation.IReference`1 <Windows.UI.Text.FontStyle>每個項目。

當我調試時,就我的代碼而言,一切都是一樣的和罰款。

我的控件使用名爲SelectedItemEnum的DependencyProperty - SelectedItemEnumProperty,它的type是對象。 並以此綁定具體枚舉值它設置的ItemsSource:(我處理SelectionChanged事件(控制內)來設置值,但該部分很管用)

ItemsSource = Enum.GetValues(SelectedItemEnum.GetType()).Cast<Enum>().ToList(); 

回答

0

我現在已經嘗試了一個小時左右,但我無法弄清楚爲什麼發生這種情況,我一定會有興趣看到背後的真正原因..顯然有一些關於FontStyle枚舉,導致它得到表示爲可空(IReference在.NET環境中似乎爲"equivalent" to nullable)。

但是,要解決您的問題,您可以構建一個自定義的ValueConverter,在顯示之前將該值轉換爲字符串。

首先創建一個ToStringConverter

public class ToStringConverter : IValueConverter 
{ 
    public object Convert(object value, Type targetType, object parameter, string language) 
    { 
     var stringValue = value.ToString(); 
     return stringValue; 
    } 

    public object ConvertBack(object value, Type targetType, object parameter, string language) 
    { 
     throw new NotImplementedException(); 
    } 
} 

現在添加是作爲資源到您的網頁或應用程序本身:

<Page.Resources> 
    <local:ToStringConverter x:Key="ToStringConverter" /> 
</Page.Resources> 

然後,您可以用組合框使用,如下所示:

<local:EnumComboBox x:Name="EnumComboBox"> 
    <local:EnumComboBox.ItemTemplate> 
     <DataTemplate> 
      <TextBlock Text="{Binding Converter={StaticResource ToStringConverter}}" /> 
     </DataTemplate> 
    </local:EnumComboBox.ItemTemplate> 
</local:EnumComboBox> 

這將正確顯示枚舉的值。你可以看到它並在here on my GitHub中試用它,以及我用來試圖弄清楚的示例應用程序。

但是我會繼續努力尋找原因,因爲它真的讓我感興趣:-)。