2011-12-08 36 views
14

Tôi muốn làm như sau khi chạy trong mã:Làm cách nào để tạo một biểu dữ liệu với nội dung theo chương trình?

<DataTemplate x:Key="lightGreenRectangle"> 
     <Rectangle Fill="LightGreen"/> 
    </DataTemplate> 

Cho đến nay tôi đã có:

public DataTemplate GetColouredRectangleInDataTemplate(Color colour) 
{ 
    DataTemplate dataTemplate = new dataTemplate(); 

    return dataTemplate; 
} 

Trợ giúp? Tôi biết đây không phải là cách thanh lịch nhất để tạo kiểu cho một điều khiển, nhưng thành phần tôi muốn chỉ định một màu cho một thuộc tính có tên là "PointTemplate" của kiểu DataTemplate.

+1

Nếu bạn muốn tạo kiểu điều khiển, bạn nên sử dụng ControlTemplate, Biểu dữ liệu sẽ hiển thị dữ liệu theo cách cụ thể. Quay lại câu hỏi của bạn, bạn muốn đặt màu cho điều gì? – MBen

+0

hoạt động như thế này có phù hợp với bạn không? DataTemplate asd = new DataTemplate(); asd.DataType = typeof (Rectangle); asd.VisualTree.SetValue (Rectangle.FillProperty, Brushes.Green); – peer

Trả lời

24

Nếu vì bất cứ lý do bạn cần phải tạo ra một DataTemplate lập trình bạn sẽ làm gì:

XAML:

<Grid x:Name="myGrid"> 
    <ContentControl ContentTemplate="{DynamicResource lightGreenRectangle}" /> 
</Grid> 

Một nơi nào đó trong mã của bạn:

public static DataTemplate CreateRectangleDataTemplate() 
    { 
     var rectangleFactory = new FrameworkElementFactory(typeof(Rectangle)); 
     rectangleFactory.SetValue(Shape.FillProperty, new SolidColorBrush(System.Windows.Media.Colors.LightGreen)); 

     return new DataTemplate 
        { 
         VisualTree = rectangleFactory, 
        }; 
    } 

    public static void AddRectangleTemplateToResources(FrameworkElement element) 
    { 
     element.Resources.Add("lightGreenRectangle", CreateRectangleDataTemplate()); 
    } 

Sau đó, bạn chỉ cần thêm các DataTemplate đến một ResourceDictionary để nó có thể được sử dụng. Ví dụ: trong mã phía sau:

public MainWindow() 
    { 
     InitializeComponent(); 
     AddRectangleTemplateToResources(myGrid); 
    } 

Hy vọng điều này sẽ hữu ích!

+0

Nó đã làm. Cảm ơn bạn. – Corpsekicker

+0

Điều này có thể cho Silverlight không? –

+0

Nevermind, được tìm thấy: http://blogs.msdn.com/b/scmorris/archive/2008/04/14/defining-silverlight-datagrid-columns-at-runtime.aspx –

6

Sử dụng lớp helper sau:

/// <summary> 
/// Class that helps the creation of control and data templates by using delegates. 
/// </summary> 
public static class TemplateGenerator 
{ 
    private sealed class _TemplateGeneratorControl: 
    ContentControl 
    { 
    internal static readonly DependencyProperty FactoryProperty = DependencyProperty.Register("Factory", typeof(Func<object>), typeof(_TemplateGeneratorControl), new PropertyMetadata(null, _FactoryChanged)); 

    private static void _FactoryChanged(DependencyObject instance, DependencyPropertyChangedEventArgs args) 
    { 
     var control = (_TemplateGeneratorControl)instance; 
     var factory = (Func<object>)args.NewValue; 
     control.Content = factory(); 
    } 
    } 

    /// <summary> 
    /// Creates a data-template that uses the given delegate to create new instances. 
    /// </summary> 
    public static DataTemplate CreateDataTemplate(Func<object> factory) 
    { 
    if (factory == null) 
     throw new ArgumentNullException("factory"); 

    var frameworkElementFactory = new FrameworkElementFactory(typeof(_TemplateGeneratorControl)); 
    frameworkElementFactory.SetValue(_TemplateGeneratorControl.FactoryProperty, factory); 

    var dataTemplate = new DataTemplate(typeof(DependencyObject)); 
    dataTemplate.VisualTree = frameworkElementFactory; 
    return dataTemplate; 
    } 

    /// <summary> 
    /// Creates a control-template that uses the given delegate to create new instances. 
    /// </summary> 
    public static ControlTemplate CreateControlTemplate(Type controlType, Func<object> factory) 
    { 
    if (controlType == null) 
     throw new ArgumentNullException("controlType"); 

    if (factory == null) 
     throw new ArgumentNullException("factory"); 

    var frameworkElementFactory = new FrameworkElementFactory(typeof(_TemplateGeneratorControl)); 
    frameworkElementFactory.SetValue(_TemplateGeneratorControl.FactoryProperty, factory); 

    var controlTemplate = new ControlTemplate(controlType); 
    controlTemplate.VisualTree = frameworkElementFactory; 
    return controlTemplate; 
    } 
} 

Bạn có thể tạo dữ liệu mẫu như thế này:

DataTemplate template = 
    TemplateGenerator.CreateDataTemplate 
    (
    () => 
    { 
     var result = new TextBox() 
     result.SetBinding(TextBox.TextProperty, "BindingPathHere"); 
     return result; 
    } 
); 

Bạn có thể tự do sử dụng bất kỳ mã để tạo ra sự kiểm soát như bạn sẽ làm gì nếu bạn đã tạo điều khiển trực tiếp, không có bất kỳ mẫu dữ liệu nào. Để biết thêm thông tin, hãy xem mẹo này trong dự án mã: http://www.codeproject.com/Tips/808808/Create-Data-and-Control-Templates-using-Delegates

Các vấn đề liên quan