我在PhoneApplicationPage.Resources中有这种风格:
<phone:PhoneApplicationPage.Resources>
<data:CarListView x:Key="carCollection" />
<Style x:Key="ListBoxItemStyle1" TargetType="ListBoxItem">
<Setter Property="Template">
....
我正在尝试向StackPanel添加一个只有一个项目的新ListBox。它只显示了类的名称。我尝试了很多方法。例如:
ListBox lstBox = new ListBox();
CarListView view = new CarListView();
view.DataCollection.Add(new CarView("John", "Ferrari", "/Images/car_missing.jpg"));
lstBox.ItemsSource = view.DataCollection;
lstBox.Style = Application.Current.Resources["ListBoxItemStyle1"] as Style;
stackPanel.Children.Insert(0, lstBox);
风格和类别没问题。当我没有在代码中添加此内容但在xaml中加载页面时,一切看起来都很好。如何从代码中添加来自资源样式的新列表框?
答案 0 :(得分:0)
你必须使用ItemContainerStyle作为listboxitems,Style是ListBox控件!
<Grid x:Name="LayoutRoot" Background="White">
<Grid.Resources>
<Style x:Key="myLBStyle" TargetType="ListBoxItem">
<Setter Property="Background" Value="Khaki" />
<Setter Property="Foreground" Value="DarkSlateGray" />
<Setter Property="Margin" Value="5" />
<Setter Property="FontStyle" Value="Italic" />
<Setter Property="FontSize" Value="14" />
<Setter Property="BorderBrush" Value="DarkGray" />
</Style>
</Grid.Resources>
<ListBox Height="184" ItemContainerStyle="{StaticResource myLBStyle}" HorizontalAlignment="Left"
Margin="23,24,0,0" Name="listBox1" VerticalAlignment="Top" Width="204" >
<ListBox.Items>
<ListBoxItem Content="Item1" />
<ListBoxItem Content="Item2" />
<ListBoxItem Content="Item3" />
</ListBox.Items>
</ListBox>
</Grid>
或代码:
listBox1.ItemContainerStyle = Application.Current.Resources["myLBStyle"] as Style;
答案 1 :(得分:0)
我已经制作了一个示例,我在代码中创建了所有内容,并从示例中的页面资源中加载样式
XAML:
<phone:PhoneApplicationPage.Resources>
<Style x:Key="myLBStyle"
TargetType="ListBoxItem">
<Setter Property="Background"
Value="Khaki" />
<Setter Property="Foreground"
Value="DarkSlateGray" />
<Setter Property="Margin"
Value="5" />
<Setter Property="FontStyle"
Value="Italic" />
<Setter Property="FontSize"
Value="14" />
<Setter Property="BorderBrush"
Value="DarkGray" />
</Style>
</phone:PhoneApplicationPage.Resources>
然后我有一个空的stackpanel,我在用户点击按钮时添加列表框
文件背后的代码:
private void Test_Click_1(object sender, System.Windows.RoutedEventArgs e)
{
ListBox lstBox = new ListBox();
List<string> data = new List<string>() { "one", "two", "three" };
lstBox.ItemsSource = data;
lstBox.ItemContainerStyle = this.Resources["myLBStyle"] as Style;
MyStackPanel.Children.Insert(0, lstBox);
}