WPF -How to access the fields present in a template

Viewed 44

Let me explain so I have a wpf application I used a listBox with a template. This template contains a TextBlock and a ComboBox. When running the application, everything goes well, my list is initialized correctly. But then I would like to retrieve the values ​​of my TextBlock and my comboBox and I don't understand how I can achieve this.

I am attaching the part of my XAML code that deals with this listBox :

    <ListBox x:Name="ListBoxEnv" Grid.Row="1"
            d:ItemsSource="{d:SampleData ItemCount=5}" Width="460"
            SelectionChanged="ListBoxEnv_SelectionChanged">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Horizontal">
                    <TextBlock x:Name="TxtBlockEnv"
                            VerticalAlignment="Center" HorizontalAlignment="Left"
                            Text="{Binding EnvName}"/>
                    <ComboBox x:Name="ComboBoxEnv"
                                VerticalAlignment="Center" HorizontalAlignment="Left"
                                ItemsSource="{Binding EnvListValue}"
                                Margin="100,2,0,2" Width="200"
                                SelectionChanged="ComboBoxEnv_SelectionChanged"/>
                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
1 Answers

The EnvName property is readonly because it is bound to TextBlock, so you can ignore it. Change binding to: Text="{Binding EnvName, Mode=OneTime}" to save the app resources.

However to extract selected environment in every combo in the list you need to add to ComboBox template: SelectedItem={Binding SelectedEnv} and add new property to SampleData

for example

public MyEnvironmentClass SelectedEnv {get; set;} 
Related