Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
442 views
in Technique[技术] by (71.8m points)

c# - 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 ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...