创建后面的datatemplate代码

时间:2012-12-27 11:18:10

标签: c# wpf c#-4.0

我正在尝试为show数据创建一个ListBox视图,我希望它包含一个带有2列数据模板的ListBox“Product ID& Product Barcode”

我想使用纯C#代码创建它,或者如果可能通过xaml加载它?如果我可以创建一个模板,我可以使用c#作为各种资源。

到目前为止我所做的是: 在XAML中:

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="37*" />
        <RowDefinition Height="88*" />
    </Grid.RowDefinitions>
    <TextBlock Text="Type Your Search :" HorizontalAlignment="Left"  VerticalAlignment="Bottom" Width="112" Height="15.96" Margin="20,0,0,4" />

    <TextBox HorizontalAlignment="Right" VerticalAlignment="Bottom" Height="25" Width="300" Margin="0,0,44,0" x:Name="txtCAuto" TextWrapping="NoWrap" HorizontalContentAlignment="Right" />

    <ListBox x:Name="lbSuggestion" SelectionChanged="lbSuggestion_SelectionChanged" Foreground="Black" Width="300" Margin="0,0,44,0"  FlowDirection="RightToLeft" Background="LightYellow" Grid.Row="1" Visibility="Collapsed"  ScrollViewer.HorizontalScrollBarVisibility="Auto" ItemsSource="{Binding}"  HorizontalAlignment="Right" VerticalAlignment="Top" HorizontalContentAlignment="Right" BorderBrush="Transparent"  Grid.IsSharedSizeScope="True">
    </ListBox>
</Grid>

代码背后:

string typedString = txtCAuto.Text.ToUpper();
        List<string> autoList = new List<string>();
        autoList.Clear();

         prodDetails ps = SelProd4Sale();

        foreach (string item in ps.ProdBrcdList)
        {
            if (!string.IsNullOrEmpty(txtCAuto.Text))
            {
                if (item.StartsWith(typedString))
                {
                    //autoList.Add(item);
                    FrameworkElementFactory colProdID = new FrameworkElementFactory(typeof(TextBlock));
                    Binding prodID = new Binding(ps.ProdIDList.ToString());
                    colProdID.SetBinding(TextBlock.TextProperty, prodID);

                    FrameworkElementFactory colProdBarcode = new FrameworkElementFactory(typeof(TextBlock));
                    Binding prodBarcode = new Binding();
                    prodBarcode.Path = new PropertyPath(ps.ProdBrcdList.ToString());
                    colProdBarcode.SetBinding(TextBlock.TextProperty, prodBarcode);


                    FrameworkElementFactory sb = new FrameworkElementFactory(typeof(StackPanel));
                    sb.AppendChild(colProdID);
                    sb.AppendChild(colProdBarcode);

                    dTemplate = new DataTemplate { VisualTree = sb };
                    dTemplate.Seal();


                }
            }
        }

        if (autoList.Count > 0)
        {
            lbSuggestion.ItemTemplate = dTemplate;
            //lbSuggestion.ItemsSource = autoList;
            lbSuggestion.Visibility = Visibility.Visible;
        }
        else if (txtCAuto.Text.Equals(""))
        {
            lbSuggestion.Visibility = Visibility.Collapsed;
            lbSuggestion.ItemsSource = null;
        }
        else
        {
            lbSuggestion.Visibility = Visibility.Collapsed;
            lbSuggestion.ItemsSource = null;
        }

但是没有数据出现,请提出任何建议。 感谢,

3 个答案:

答案 0 :(得分:7)

您可以在xaml中定义资源,如果已定义x:Key,则在代码后面检索它。

在你的xaml中:

<DataTemplate x:Key="anyId">...</DataTemplate>

在您的代码中:

var dataTemplate = Application.Current.TryFindResource("anyId") as DataTemplate;

var dataTemplate = Application.Current.FindResource("anyId") as DataTemplate;

答案 1 :(得分:4)

我已经创建了这样的DataTemplate:

private DataTemplate getDataTemplate()
{
    DataTemplate retVal = null;
    String markup = String.Empty;

    markup = "<DataTemplate xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\" xmlns:local=\"clr-namespace:YOUR.PROJECT.NAMESPACE;assembly=YOUR.PROJECT.NAMESPACE\">";
    markup += "<Grid>";
    markup += "<TextBlock Text=\"{Binding RelativeSource={RelativeSource Mode=TemplatedParent}, Path=Content, Mode=OneWay}\" />";
    markup += "</Grid>";
    markup += "</DataTemplate>";

    retVal = (DataTemplate)XamlReader.Load(markup);

    return retVal;
}

...然后在需要的地方调用此方法(如OnApplyTemplate)

this.ContentTemplate = getDataTemplate();

注意:您可能必须更改WPF的“xmlns”,因为此示例来自我的一个Silverlight项目。但这个想法是一样的。

答案 2 :(得分:1)

条件XAML DataTemplate

在对象的XAML文件中定义静态DataTemplate是解决此问题的常用方法。此外,Microsoft提供的示例DataTemplate.LoadContent()非常适合显示如何在运行时动态切换模板(请参阅DataTemplate.LoadContent method)。

但是,如果您对条件XAML编译有特殊要求(比如在构建发行版时省略仅调试XAML),则需要采用XamlReader.Load()方法(请参阅{ {3}})。

为此,我认为更详细的例子可能会有所帮助。在这里,我有一个仅调试的ListView绑定到ObservableCollection&lt;&gt;自定义对象。 ListView没有在静态XAML中定义,因为它只在调试模式中需要...


自定义类:

    class ActiveNotification
    {
        public String Name { get; set; }
        public String Type { get; set; }
        public String DayOfWeek { get; set; }
        public DateTime DeliveryTime { get; set; }
        public String Id { get; set; }
    }

私人成员变量:

    readonly ObservableCollection<ActiveNotification> _activeNotifications = new ObservableCollection<ActiveNotification>();
    readonly ListView listViewNotifications = 
        new ListView 
        { 
            Visibility = Visibility.Collapsed,
            HorizontalAlignment = HorizontalAlignment.Left,
            VerticalAlignment = VerticalAlignment.Bottom,
        };

加载时ListView设置:

        // Set up notifications list
        listViewNotifications.SetBinding(ListView.ItemsSourceProperty, new Binding { Source = _activeNotifications });
        listViewNotifications.Tapped += listViewNotifications_Tapped;
        Grid.SetRowSpan(listViewNotifications, 2);
        Grid.SetColumnSpan(listViewNotifications, 2);
        var xamlString =
            "<DataTemplate xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\">" +
                "<StackPanel Orientation=\"Horizontal\" VerticalAlignment=\"Center\">" +
                    "<TextBlock Text=\"{Binding Name}\" Margin=\"20,0,10,0\"/>" +
                    "<TextBlock Text=\"{Binding Type}\" Margin=\"0,0,10,0\"/>" +
                    "<TextBlock Text=\"{Binding DayOfWeek}\" Margin=\"0,0,10,0\"/>" +
                    "<TextBlock Text=\"{Binding DeliveryTime}\" Margin=\"0,0,10,0\"/>" +
                    "<TextBlock Text=\"{Binding Id}\"/>" +
                "</StackPanel>" +
            "</DataTemplate>";
        var dataTemplate = (DataTemplate)XamlReader.Load(xamlString);
        listViewNotifications.ItemTemplate = dataTemplate;
        GridMain.Children.Add(listViewNotifications);

希望这有帮助!

标记