首页 文章

有没有办法直观地创作WPF自定义控件?

提问于
浏览
1

有没有办法使用可视化XAML设计器来创作WPF Custom Controls ,就像使用用户控件一样?

据我所知,在Visual Studio 2010和2012中没有这样的东西 . 我也看过Expression Blend 4,但似乎没有人支持这一点 .

我发现这很难相信,因为在我看来这将是一个明显和必要的功能 .

为了清楚起见,我正在寻找一个XAML编辑器,在这里我可以直观地看到XAML的结果作为渲染控件,就像我使用它一样,就像在Visual Studio 2010中创建用户控件一样 .

1 回答

  • 1

    这是我提出的一件事:

    • 在Visual Studio 2010中,创建一个新的WPF自定义控件项目 .

    • 添加名为 CustomControl1Dictionary.xaml 的新资源字典 .

    • 添加名为 CustomControl1View.xaml 的新用户控件 .

    • 更改项目中的代码,如下所示:

    CustomControl1Dictionary.xaml

    <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                        xmlns:local="clr-namespace:WpfCustomControlLibrary1">
        <Style TargetType="{x:Type local:CustomControl1}">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type local:CustomControl1}">
                        <Border Background="{TemplateBinding Background}"
                                BorderBrush="{TemplateBinding BorderBrush}"
                                BorderThickness="{TemplateBinding BorderThickness}">
                            <TextBlock VerticalAlignment="Center" HorizontalAlignment="Center" FontSize="30" FontWeight="Bold">This freaking sucks!</TextBlock>
                        </Border>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>    
    </ResourceDictionary>
    

    Themes\Generic.xaml

    <ResourceDictionary
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="/WpfCustomControlLibrary1;component/CustomControl1Dictionary.xaml" />
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
    

    CustomControl1View.xaml

    <UserControl x:Class="WpfCustomControlLibrary1.CustomControl1View"
                 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                 xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
                 xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
                 xmlns:local="clr-namespace:WpfCustomControlLibrary1"
                 mc:Ignorable="d" 
                 d:DesignHeight="292" d:DesignWidth="786">
        <local:CustomControl1 />
    </UserControl>
    

    这让我可以打开用户控件作为弹出窗口,在构建项目并单击用户控件设计器后,我可以看到我在自定义控件资源字典中对XAML所做的更改 .

相关问题