简体   繁体   中英

WPF ItemsControl get the XAML elements programmatically?

I have a ItemsControl filled with a ModelView and this XAML markup:

<ItemsControl.ItemTemplate>
    <DataTemplate>
        <StackPanel Orientation="Horizontal" Margin="0, 0, 0, 5">
            <TextBlock Text="{Binding Value}" Margin="5, 2, 0, 0" />
        </StackPanel>
    </DataTemplate>
</ItemsControl.ItemTemplate>

I want to get the TextBlock element programmatically so I can change it's style after validating the data, how can I do this?

Add name to items control, for example:

<StackPanel x:Name="MyStack" Orientation="Horizontal" Margin="0, 0, 0, 5">
    <TextBlock Text="{Binding Value}" Margin="5, 2, 0, 0" />
</StackPanel>

Add a StackPanel public Property in your CustomControl, for example:

public StackPanel ItemsControl {get;set;}

And override the OnApplyTemplate of your custom control to:

protected override void OnApplyTemplate()
{
    ItemsControl = GetTemplateChild("MyStack") as StackPanel;
}

And you will be able to access the stackpanel and its children.

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