Access a control from within a DataTemplate with its identifying name

前端 未结 3 1824
醉话见心
醉话见心 2020-12-10 22:14

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:



        
相关标签:
3条回答
  • 2020-12-10 22:37

    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!

    0 讨论(0)
  • 2020-12-10 22:37

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

    You can try to read about some workarounds for example

    • WPF - Find a Control from DataTemplate in WPF

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

    • here
    • here
    • here
    • here
    • here
    • here
    • here
    • here
    0 讨论(0)
  • 2020-12-10 22:51

    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 :

    • How to: Find ControlTemplate-Generated Elements
    0 讨论(0)
提交回复
热议问题