简体   繁体   中英

Access a control from within a DataTemplate with its identifying name

In my WPF application I have a ComboBox control that is located inside a Grid Control. In XAML I am assigning a name to the ComboBox:

<DataGridTemplateColumn Header="Status">
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <TextBlock VerticalAlignment="Center" Text="{Binding name_ru}" Width="Auto" />
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
    <DataGridTemplateColumn.CellEditingTemplate>
        <DataTemplate>
            <ComboBox Name="stcom" Style="{DynamicResource ComboBoxStyle}" SelectionChanged="status_SelectionChanged" Height="auto" Width="Auto">
                 <ComboBox.BorderBrush>
                     <SolidColorBrush Color="{DynamicResource Color1}"/>
                 </ComboBox.BorderBrush>
            </ComboBox>
        </DataTemplate>
    </DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>

With the method FindName(string) I am trying to refer to the ComboBox with its associated name:

ComboBox stcom
        {
            get
            {
                return (ComboBox)FindName("stcom");
            }
        }


 if (stcom != null)
            {
                stcom.ItemsSource = list;
            }

But obviously the control can not be found because the reference stcom remains null.

The question now is how to refer to my ComboBox using its name property ?

The answer is:

<Style x:Key="CheckBoxStyle1" TargetType="{x:Type CheckBox}">
  <Setter Property="Template">
   <Setter.Value>
    <ControlTemplate TargetType="{x:Type CheckBox}">
     <StackPanel Orientation="Horizontal">
      <Grid>
       <TextBlock Name="tbUserIcon" Text="t1" />
       <TextBlock Name="tbCheck"  Text="✓" />
      </Grid>
     </StackPanel>
    </ControlTemplate>
   </Setter.Value>
  </Setter>
 </Style>

and C#:

checkBox.ApplyTemplate();
var tbUserIcon= (TextBlock)checkBox.Template.FindName("tbUserIcon", checkBox);

don't forget the checkBox.ApplyTemplate() be fore Template.FindName() it's important!

First you have to get access to the control template which it has been applied to, then you can find an element of the template by name. Have a look at the MSDN knowledge base :

You can't access controls that are part of a DataTemplate with their name.

You can try to read about some workarounds for example

You can also have a look at the dozens of posts here on SO issuing this topic for example

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