C# 4.0 在wpf中基于组合框项目选择显示图像
我有一个组合框,其中包含以下项目: 项目1 项目2 项目3C# 4.0 在wpf中基于组合框项目选择显示图像,c#-4.0,wpf-4.0,C# 4.0,Wpf 4.0,我有一个组合框,其中包含以下项目: 项目1 项目2 项目3 对应的每个项目都有图像,比如项目1有图像img1.jpg,项目2有图像img2.jpg,项目3有图像img3.jpg。当我们从combox中选择项目时,它将在标签中显示相应的图像。我得到了问题的答案,如下所示: <xmlns:local="clr-namespace:ImageMVVM_Learning" Title="MainWindow" Height="350" Width="525"> <Wi
对应的每个项目都有图像,比如项目1有图像img1.jpg,项目2有图像img2.jpg,项目3有图像img3.jpg。当我们从combox中选择项目时,它将在标签中显示相应的图像。我得到了问题的答案,如下所示:
<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>
读者请注意:上面的XML片段是为了在堆栈溢出时呈现而故意损坏的。我已经使用提供的代码格式化工具尽可能地修复了它,但值得在其他地方检查它是否正确。欢迎编辑以更正它。
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;
}
}