【问题标题】:Display image based on combobox item selection in wpf根据wpf中的组合框项目选择显示图像
【发布时间】:2014-05-15 10:53:51
【问题描述】:

我有一个组合框,其中有一些项目,例如:

  1. 项目1

  2. 项目2

  3. 项目3

对应每个item都有图片,比如item1有图片img1.jpg,item2有图片img2.jpg,item3有图片img3.jpg。当我们从combox中选择item时,它会在label中显示对应的图片。

【问题讨论】:

    标签: c#-4.0 wpf-4.0


    【解决方案1】:

    我的问题得到了答案,这里是:

    <xmlns:local="clr-namespace:ImageMVVM_Learning"
            Title="MainWindow" Height="350" Width="525">
    
    <Window.Resources>
        <local:EnumToImageConverter x:Key="conv"/>
    </Window.Resources>
    
        <Grid>
            <StackPanel>
                <ComboBox x:Name="combo" ItemsSource="{Binding MyProperty}"/>
                <Image Source="{Binding ElementName=combo,Path=SelectedValue,Converter={StaticResource conv}}"/>
            </StackPanel>
        </Grid>
    
    </Window>
    

    在您的视图模型类中执行此操作:

    public enum MyEnum
    {
        A,
        B,
        C
    }
    
    public class EnumToImageConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value != null)
            {
                switch ((MyEnum)value)
                {
                    case MyEnum.A:
                        return new BitmapImage(new Uri(@"Images\A.png", UriKind.Relative));
                    case MyEnum.B:
                        return new BitmapImage(new Uri(@"Images\B.png", UriKind.Relative));
                }
            }
            return new BitmapImage(new Uri(@"Images\A.png", UriKind.Relative));
        }
    
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {            
            return null;
        }
    }
    

    【讨论】:

    • 读者请注意:上面的 XML sn-p 被故意损坏以使其在 Stack Overflow 上呈现。我已经尽我所能修复了它(使用提供的代码格式化工具),但值得在别处检查它是否正确。欢迎进行编辑以纠正它。
    猜你喜欢
    • 1970-01-01
    • 2021-12-23
    • 2015-01-23
    • 1970-01-01
    • 2015-08-10
    • 1970-01-01
    • 1970-01-01
    • 2013-03-09
    • 1970-01-01
    相关资源
    最近更新 更多