0

我在 PhoneApplicationPage.Resources 中有这种风格:

<phone:PhoneApplicationPage.Resources>
    <data:CarListView x:Key="carCollection" />
    <Style x:Key="ListBoxItemStyle1" TargetType="ListBoxItem">
        <Setter Property="Template">
        ....

我正在尝试将仅包含一项的新 ListBox 添加到 StackPanel。它只显示类的名称。我尝试了很多方法。例如这个:

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

4

2 回答 2

0

您必须为列表框项使用 ItemContainerStyle,样式用于 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;
于 2013-02-18T21:12:42.813 回答
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>

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

文件背后的代码:

    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);
    }
于 2013-02-19T13:33:38.537 回答