Bind Icon depending on Enum in WPF Treeview

前端 未结 3 860
后悔当初
后悔当初 2020-12-18 19:24

I have at treeview TextBox, and I want convert my Enum:



        
相关标签:
3条回答
  • 2020-12-18 19:59

    You should use Binding with value converter: http://blogs.msdn.com/bencon/archive/2006/05/10/594886.aspx

    0 讨论(0)
  • 2020-12-18 20:00

    Create a Value Converter

    It takes your enum value and returns the filename of the appropriate icon.

    [ValueConversion(typeof(AcceptationStatusGlobalFlag), typeof(string))]
    public class AcceptationStatusGlobalFlagToIconFilenameConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            switch ((AcceptationStatusGlobalFlag)value)
            {
                case AcceptationStatusGlobalFlag.Ready:
                    return "ready.jpg";
                case AcceptationStatusGlobalFlag.NotReady:
                    return "notready.jpg";
                case AcceptationStatusGlobalFlag.AcceptedByAdmin:
                    return "AcceptedByAdmin.jpg";
                default:
                    return null;
            }
    
            // or
            return Enum.GetName(typeof(AcceptationStatusGlobalFlag), value) + ".jpg";
        }
    
        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotSupportedException();
        }
    }
    

    You will need to add a reference to this converter in your XAML

    <Window ... xmlns:converters="clr-namespace:App.Converters" ...>
        <Window.Resources>
            <converters:AcceptationStatusGlobalFlagToIconFilenameConverter x:Key="IconConverter"/>
        </Window.Resources>
    

    Replace your TextBlock

    <TextBlock TextAlignment="Justify" VerticalAlignment="Center" Text="{Binding Path=AcceptationStatusGlobalFlag}" />
    

    with an Image and tell it use your converter

    <Image Source="{Binding AcceptationStatusGlobalFlag, Converter={StaticResource IconConverter}}"/>
    
    0 讨论(0)
  • 2020-12-18 20:09

    The most easy solution to this, is to use a value convertor; so create an IValueConverter implementation that converts your enums to the corresponding images.

    For more information see: http://msdn.microsoft.com/en-us/library/system.windows.data.ivalueconverter.aspx

    0 讨论(0)
提交回复
热议问题