从PhoneResources获取样式并应用于新的ListBox

本文关键字:ListBox 应用于 PhoneResources 获取 样式 | 更新日期: 2023-09-27 18:00:03

我在PhoneApplicationPage中有这种风格。资源:

<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中添加时,一切看起来都很好。如何从具有资源样式的代码中添加新列表框?

从PhoneResources获取样式并应用于新的ListBox

我制作了一个示例,在代码中创建所有样式,并从页面资源中加载样式,如示例中所示

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>

然后我有一个空的堆叠面板,当用户点击按钮时,我会在其中添加列表框

文件背后的代码:

    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);
    }

您必须为listboxitems使用ItemContainerStyle,该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;