【问题标题】:How dynamically create PanoramaItem control in c#?如何在 C# 中动态创建 PanoramaItem 控件?
【发布时间】:2023-03-28 09:34:02
【问题描述】:
**<controls:PanoramaItem Header="first item">
            <!--Double line list with text wrapping-->
            <ListBox Margin="0,0,-12,0" ItemsSource="{Binding Items}">
                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <StackPanel Margin="0,0,0,17" Width="432" Height="150">
                            <StackPanel Orientation="Horizontal">
                                <TextBlock x:Name="Name" Text="Name: " TextWrapping="Wrap" Style="{StaticResource PhoneTextExtraLargeStyle}"/>
                                <TextBlock Text="{Binding LineOne}" TextWrapping="Wrap" Style="{StaticResource PhoneTextExtraLargeStyle}" Margin="5,0,0,0"/>
                            </StackPanel>
                            <TextBlock Text="{Binding LineTwo}" TextWrapping="Wrap" Margin="12,-6,12,0" Style="{StaticResource PhoneTextSubtleStyle}"/>
                            <TextBlock Text="{Binding LineThree}" TextWrapping="Wrap" Margin="12,-6,12,0" Style="{StaticResource PhoneTextSubtleStyle}"/>
                            <TextBlock Text="{Binding LineFour}" TextWrapping="Wrap" Margin="12,-6,12,0" Style="{StaticResource PhoneTextSubtleStyle}"/>
                        </StackPanel>
                    </DataTemplate>
                </ListBox.ItemTemplate>



            </ListBox>
        </controls:PanoramaItem>**

这是 .xmal 部分。但我必须在 c# 中执行此操作。然后请帮助我如何执行此操作。

【问题讨论】:

    标签: c#


    【解决方案1】:
    ListBox listBox = new ListBox();
    listBox.Margin = new Thickness(0, 0, -12, 0);
    listBox.SetBinding(ListBox.ItemsSourceProperty, new Binding("Items"))
    
    CreateItemTemplate(listBox);
    
    PanoramaItem pi = new PanoramaItem();
    pi.Header = "first item";
    pi.Content = listBox;
    

    在实现CreateItemTemplate 时,您有两个选择,以编程方式创建DataTemplate 或在ResourceDictionary 中创建它作为资源并使用该资源。后者是迄今为止最简单和最好的方法。

    要以编程方式执行此操作,请参阅 How to define a DataTemplate in code?

    要使用资源,您可以这样做

    public void CreateItemTemplate(ListBox listBox)
    {
        object myDataTemplate = FindResource("myDataTemplateResource"); // This only works if the resource is available in the scope of your control. E.g. is defined in MyControl.Resources
        listBox.SetResourceReference(ListBox.ItemTemplateProperty, myDataTemplate);
    }
    

    【讨论】:

      猜你喜欢
      • 2017-07-22
      • 1970-01-01
      • 2017-12-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多