How to access a control located inside a data template from a list?

Hi I have the following code:

<ListBox x:Name="foldersListBox" Grid.Column="0" MouseLeftButtonUp="foldersListBox_MouseLeftButtonUp" BorderThickness="0" Height="AUTO" ScrollViewer.HorizontalScrollBarVisibility="Disabled" ScrollViewer.VerticalScrollBarVisibility="Disabled"> <DataTemplate> <Border BorderBrush="LightGray" BorderThickness="2" CornerRadius="4"> <Image x:Name="folderImage" Width="70" Height="70" Margin="3" /> </Border> </DataTemplate> </ListBox> 

Now when I try to access folderImage from the code behind. I can use the loaded event and assign the image type to the sender, but I do not want this because I want to bind the source of the image at the time of binding at runtime. Therefore, even if we try to load the loaded event, this will not help, since the control will not be loaded.

Help plz.

Thanks Subhen

+4
source share
1 answer

There are quite a few details in your question, but I will still be responsible for the answer. Its very unlikely to answer your question, but it can help you understand what detail you need to add a question to guide the answers. In turn, this answer can be clarified. Some iterations along the way, you really can get an answer.

I'm going to guess that you are attached to a set of objects that represent "Folders", but you want to programmatically change the displayed image depending on the state of each object, for example, some FolderType property.

In solving this issue, a value converter is used if your images have a finite set.

 public class FolderToImageConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { Folder folder = value as Folder; ImageSource result; // Logic to determine which ImageSource to use for a folder. return result; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } } 

Now take a look at this XAML: -

 <Grid x:Name="LayoutRoot"> <Grid.Resources> <local:FolderToImageConverter x:Key="ImageConverter" /> </Grid.Resources> <ListBox x:Name="foldersListBox"> <ListBox.ItemTemplate> <DataTemplate> <Border BorderBrush="LightGray" BorderThickness="2" CornerRadius="4"> <Image Source="{Binding Converter={StaticResource ImageConverter}}" Width="70" Height="70" Margin="3" /> </Border> </DataTemplate> </ListBox.ItemTemplate> </ListBox> </Grid> 

Once you have linked your collection of Folder objects to a ListBox ItemsSource , it will display a set of images using a converter to convert the Folder object to the correct ImageSource instance.

+1
source

Source: https://habr.com/ru/post/1306444/


All Articles