stef
stef

Reputation: 71

List box modify datatemplate of items at runtime from code behind

i have this listbox

<ListBox x:Name="lbsample" ItemsSource="{Binding CurrentSettings}" SelectionMode="Extended">
    <ListBox.ItemContainerStyle>
        <Style TargetType="ListBoxItem"  >
            <Setter Property="Focusable" Value="False"/>
        </Style>
    </ListBox.ItemContainerStyle>
    <ListBox.ItemTemplate>
        <DataTemplate>
            <GroupBox x:Name="gb0" Margin="0" Background="Transparent">
                <GroupBox.Header>
                    <CheckBox x:Name="chk0" Content="xxx" 
                      IsChecked="{Binding Path=DataContext.IsEnabled, RelativeSource={RelativeSource AncestorType={x:Type ListBoxItem}}}" />
                </GroupBox.Header>
                <!---->
                <StackPanel Orientation="Horizontal" IsEnabled="{Binding Path=IsEnabled}" >
                    <TextBlock x:Name="lbltxt" Text="yyy" 
                       HorizontalAlignment="Center" VerticalAlignment="Bottom" Margin="5,5,5,10"/>
                </StackPanel>
            </GroupBox>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

when mask is loaded i want to change the text 'xxx' and 'yyy' progmatically from code behind how can i do that? i cannot reach the properties because listbox is bound and has itemsource

i know is not best practice.. but i do not have easy alternatives.. Thanks!

Upvotes: 0

Views: 94

Answers (1)

ASh
ASh

Reputation: 35646

if you need something view-specific, add Loaded event handler:

<CheckBox x:Name="chk0" Content="xxx" Loaded="CheckBoxLoaded" ...>

then in code-behind get CheckBox from sender argument and change properties:

private void CheckBoxLoaded(object sender, RoutedEventArgs e)
{
    var chk = sender as CheckBox;
}

however you can declare special property in item class and simple bind CheckBox:

<CheckBox x:Name="chk0" Content="{Binding PropertyX}" ...>

same approaches should work for TextBlock.

Upvotes: 1

Related Questions