如何在初始化期间设置DataTemplate元素 - ' System.Reflection.TargetInvocationException'

时间:2014-04-13 07:47:37

标签: c# xaml

我已经使用DataTemplate获取了这部分XAML代码:

<Grid Grid.Row="1" Visibility="Collapsed" x:Name="licenseGrid">
 <Grid.RowDefinitions>
      <RowDefinition Height="*"/>
      <RowDefinition Height="Auto"/>
 </Grid.RowDefinitions>
 <ListBox x:Name="LicensesListBox" Grid.Row="0" 
       Margin="12,10,12,0" Visibility="Visible"
       ItemsSource="{Binding Licenses}">
   <ListBox.ItemContainerStyle>
    <Style TargetType="ListBoxItem">
        <Setter Property="HorizontalContentAlignment" Value="Stretch"></Setter>
                <Setter Property="VerticalAlignment" Value="Center"></Setter>
                <Setter Property="Height" Value="Auto"></Setter>
    </Style>
   </ListBox.ItemContainerStyle>
   <ListBox.ItemTemplate>
      <DataTemplate x:Name="dt">
             <toolkit:ToggleSwitch x:Name="ts" Header="{Binding Header}"/>
      </DataTemplate>
  </ListBox.ItemTemplate>
 </ListBox>
</Grid>

在页面初始化期间,我想为ToggleSwitch元素设置一些值,但在这部分代码'library'中为null,我得到'System.Reflection.TargetInvocationException'。

public Page1()
{
    InitializeComponent();

    LicenseViewModel licenseViewModel = new LicenseViewModel();
    licenseViewModel.GetLicenses();
    this.DataContext = licenseViewModel;

    SetLicenseData();
}

private void SetLicenseData()
{
    // Code for other non DataTemplate XAML elements that works

    for (int i = 0; i < LicensesListBox.Items.Count; i++)
    {
        ListBoxItem library = (ListBoxItem)(LicensesListBox.ItemContainerGenerator.ContainerFromIndex(i));
        ToggleSwitch ts = FindFirstElementInVisualTree<ToggleSwitch>(library);
        // another lines with code...
    }
}

我想这是因为ListBox在那一刻没有完全加载,但我不知道如何解决这个问题。谢谢你的帮助。

1 个答案:

答案 0 :(得分:0)

所以我终于明白了。我将Loaded事件添加到ToggleSwitch元素,并且只使用强制转换

ToggleSwitch ts = sender as ToggleSwitch;
//another lines with code