简体   繁体   中英

How to get an icon in stackPanel in a XAML file

I am new to XAML and C#

I have an icon created already in a project and and I have to use this icon whenever I select one of the option from the dropdown menu.

I made a stackpanel in XAML file

<StackPanel Name="stackPanelforIcon">
</StackPanel>

In the code behind file I have different cases for the dropdown menu.

case IconOnSelect:
?????? = IconList.NewIcon;

This NewIcon is the one already created and I am using the source also for this

using IconProject.Iconlists;

On writing IconList.NewIcon I am not getting any error, it is referenced correctly.

What should I write at ?????? to reference it. Is there any other way apart from using stackPanel to include an icon

A StackPanel cannot show an icon on it's own. You need a control for it, for example an Image .

<StackPanel Name="stackPanelforIcon">
    <Image x:Name=theImage" />
</StackPanel>

Then you can use your Icon in your code behind like this:

this.theImage.Source = IconList.NewIcon;

You may need to convert your value, you never said what type it actually is.

Please note that using code-behind is not the preferred way with WPF. Using MVVM is way easier and more natural working with WPF, using code-behind you will fight WPF all the way. Using MVVM, this could be:

<StackPanel Name="stackPanelforIcon">
    <Image Source="{Binding CurrentImage}" />
</StackPanel>

with your ViewModel having a property called CurrentImage that you would set when you want to change it. Don't forget to implement INotifyPropertyChanged for the changes to take effect though.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM