Существует ли аналог Visual Studio (или бесплатное программное обеспечение) для функции «Редактировать шаблон» в Expression Blend? - PullRequest
0 голосов
/ 01 октября 2009

В Expression Blend вы можете просматривать и редактировать шаблон управления объектами на панели «Объекты и временная шкала». Мне интересно, есть ли в Visual Studio эквивалентная функция или есть что-то бесплатное (или очень недорогое), которое я могу скачать, что позволит мне сделать это.

Выполнение этого для DataGrid приводит к следующему:

<Style x:Key="DataGridStyle1" TargetType="{x:Type Custom:DataGrid}">
  ...
  <Setter Property="Template">
    <Setter.Value>
      <ControlTemplate TargetType="{x:Type Custom:DataGrid}">
      ...
      </ControlTemplate>
    </Setter.Value>
  </Setter>
  <Style.Triggers>
    <Trigger Property="IsGrouping" Value="True">
      <Setter Property="ScrollViewer.CanContentScroll" Value="False"/>
    </Trigger>
  </Style.Triggers>
</Style>

(..., конечно, заменяется сеттерами и содержимым шаблона управления.)

Это очень полезная отправная точка, если вы хотите создать собственный стиль и шаблон для элемента управления. Кажется, что вы можете делать практически все, что можете в Blend in Studio, но этот ускользает от меня. Есть идеи?

Редактировать

Мне также любопытно, будет ли эта функция в Visual Studio 2010. Кто-нибудь знает?

1 Ответ

0 голосов
/ 01 октября 2009

Проект SimpleStyles

Попробуйте, я думаю, что это будет то же самое. Он предоставляет вам самый простой шаблон для каждого элемента управления, поэтому вы можете использовать его в качестве отправной точки.

Код проекта для получения шаблонов:

C #

using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Markup;
using System.Xml;

namespace ControlTemplateBrowser
{
    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class Window1 : Window
    {
        private System.Windows.Forms.NotifyIcon icon;
        private WindowState _storedWindowState;
        private bool _ballonShownOnce = false;

        public Window1()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            Type controlType = typeof(Control);

            List<Type> derivedTypes = new List<Type>();

            // Search all the types in the assembly where the Control class is defined
            Assembly assembly = Assembly.GetAssembly(typeof(Control));

            foreach (Type type in assembly.GetTypes())
            {
                // Only add a type of the list if it's a Control, a concrete class, and public.
                if (type.IsSubclassOf(controlType) && !type.IsAbstract && type.IsPublic)
                {
                    derivedTypes.Add(type);
                }
            }

            // Sort the types. The custom TypeComparer class orders types alphabetically by type name.
            derivedTypes.Sort(new TypeComparer());
            lstTypes.ItemsSource = derivedTypes;

            SetupTrayIcon();
        }

        private void lstTypes_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                // Get the selected type.
                Type type = (Type)lstTypes.SelectedItem;

                // Instantiate the type
                ConstructorInfo info = type.GetConstructor(System.Type.EmptyTypes);
                Control control = (Control)info.Invoke(null);

                // Add it to the grid (but keep it hidden)
                control.Visibility = Visibility.Collapsed;
                grid.Children.Add(control);

                // Get the template.
                ControlTemplate template = control.Template;

                // Get the XAML for the template.
                XmlWriterSettings settings = new XmlWriterSettings();
                settings.Indent = true;
                StringBuilder sb = new StringBuilder();
                XmlWriter writer = XmlWriter.Create(sb, settings);
                XamlWriter.Save(template, writer);

                // Display the template
                txtTemplate.Text = sb.ToString();
                grid.Children.Remove(control);
            }
            catch (Exception err)
            {
                txtTemplate.Text = "<< Error generating template: " + err.Message + ">>";
            }
        }

        #region System tray icon code

        private void SetupTrayIcon()
        {
            // Add system tray icon
            icon = new System.Windows.Forms.NotifyIcon();
            icon.Icon = new System.Drawing.Icon("appIcon.ico");
            icon.BalloonTipIcon = System.Windows.Forms.ToolTipIcon.Info;
            icon.BalloonTipTitle = "Minimized to tray";
            icon.BalloonTipText = "Click icon to maximize.";
            icon.Visible = false;
            icon.Click += new EventHandler(icon_Click);
        }

        private void icon_Click(object sender, EventArgs e)
        {
            Show();
            WindowState = _storedWindowState;
        }

        private void Window_StateChanged(object sender, EventArgs e)
        {
            if (WindowState == WindowState.Minimized)
            {
                Hide();
                if (icon != null)
                {
                    if (!_ballonShownOnce)
                    {
                        icon.ShowBalloonTip(2000);
                        _ballonShownOnce = true;
                    }
                }
            }
            else
                _storedWindowState = WindowState;
        }

        private void Window_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            if (icon != null)
                icon.Visible = !IsVisible;
        }

        private void Window_Closed(object sender, EventArgs e)
        {
            icon.Visible = false;
            icon.Dispose();
            icon = null;
        }

        #endregion
    }

    public class TypeComparer : IComparer<Type>
    {
        #region IComparer<Type> Members

        public int Compare(Type x, Type y)
        {
            return String.Compare(x.Name, y.Name);
        }

        #endregion
    }

}

WPF:

<Window x:Class="ControlTemplateBrowser.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="WPF Control Template Browser" Height="600" Width="800" Loaded="Window_Loaded" Icon="/ControlTemplateBrowser;component/appIcon.png" Closed="Window_Closed" StateChanged="Window_StateChanged" IsVisibleChanged="Window_IsVisibleChanged">
    <Grid x:Name="grid" Margin="8">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>
        <ListBox Grid.Column="0" x:Name="lstTypes" SelectionChanged="lstTypes_SelectionChanged">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding Name}" Margin="5,0" />
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
        <TextBox Grid.Column="1" x:Name="txtTemplate" Text="Select a control to see its template." VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto" />
    </Grid>
</Window>

Скопируйте, вставьте это в свой проект и внесите необходимые изменения в пространство имен. Я думаю, что вам нужно изменить эту часть:

// Search all the types in the assembly where the Control class is defined
Assembly assembly = Assembly.GetAssembly(typeof(Control));

Чтобы получить элементы управления из другой сборки. Пусть, если вы попробовали, и как это прошло.

...