2

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 ?

marc wellman
  • 5,808
  • 5
  • 32
  • 59
kekus
  • 59
  • 1
  • 4
  • 8
  • well `FindName("stcom")` this is not working i think not looking in the controls of the grid. – V4Vendetta Jul 11 '12 at 08:44
  • if you're using Expander can take a look at http://stackoverflow.com/questions/26422811/accessing-the-children-of-an-expander-control/42381746#42381746 – yu yang Jian Feb 22 '17 at 02:51

3 Answers3

3

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!

Goliathus
  • 31
  • 2
2

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 :

Batuu
  • 595
  • 1
  • 8
  • 22
0

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

meJustAndrew
  • 6,011
  • 8
  • 50
  • 76
marc wellman
  • 5,808
  • 5
  • 32
  • 59