У меня есть некоторый шаблон кода XAML (стиль), в котором я не смог изменить текст метки (labelName), используя код c#. Пробовал гугл, но не могу найти что-то конкретное c. Похоже, есть небольшая деталь, которую я упустил.
<Style x:Key="ListBoxItemM" TargetType="{x:Type ListBoxItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ListBoxItem}">
<Border x:Name="brd" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}">
<WrapPanel>
<Grid Margin="0,0,0,0">
<Label x:Name="labelName" Content="12345" HorizontalAlignment="Left" VerticalAlignment="Top" Foreground="Black" Width="100" FontSize="20" Margin="40,25,0,0"/>
<Label Content="Price" HorizontalAlignment="Left" VerticalAlignment="Top" Foreground="Black" Width="60" Height="40" FontSize="12" Margin="180,5,0,0"/>
</Grid>
</WrapPanel>
</RadioButton>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter Property="Foreground" Value="White"/>
<Setter Property="BorderThickness" Value="1"/>
<Setter Property="BorderBrush" Value="Black"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
Код c#:
ListBoxItem item = new ListBoxItem();
item.Style = (Style)item.FindResource("ListBoxItemM");
/* Here the label is null, unfortunately */
Label nameLabel = (Label)item.Template.Resources.FindName("labelName");
nameLabel.Content = "98765";
MenuListBox.Items.Add(item);