簡體   English   中英

在后面創建數據模板代碼

[英]create datatemplate code behind

我正在嘗試為顯示數據創建一個 ListBox 視圖,我希望它包含一個 ListBox,其中包含一個用於 2 列“產品 ID 和產品條形碼”的數據模板

我想使用純 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;
        }

但是沒有數據出現,請提出任何建議。 謝謝,

您可以在 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;

我已經創建了這樣的 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 項目之一。 但想法是一樣的。

條件 XAML 數據模板

在對象的 XAML 文件中定義靜態 DataTemplate 是解決此問題的慣用方法。 此外,Microsoft 為 DataTemplate.LoadContent() 提供的示例非常適合展示如何在需要時在運行時動態切換模板(請參閱DataTemplate.LoadContent 方法)。

但是,如果您有條件 XAML 編譯的特殊要求(例如在構建發布版本時省略僅調試 XAML),您將需要求助於 XamlReader.Load() 方法(請參閱XamlReader.Load 方法)。

為此,我認為更詳細的示例可能會有所幫助。 在這里,我有一個僅限調試的 ListView,它綁定到一個 ObservableCollection<> 的自定義對象。 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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM