【发布时间】:2015-09-20 01:45:08
【问题描述】:
我的应用程序有很多窗口,其中大多数共享一些基本功能。因此,我扩展了 Window 类来为我的所有窗口创建一个基础。
一切编译和显示都很好,但是当我使用我的窗口类时,设计器只显示一个空窗口。
我做了一个可以轻松使用的基本示例,我的真实窗口要复杂得多,但这说明了问题。 代码如下:
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Markup;
namespace WpfApplication1
{
[ContentProperty("ContentElement")]
public class MyWindow : Window
{
public ToolBar ToolBar { get; private set; }
public StatusBar StatusBar { get; private set; }
public Border ContentBorder { get; private set; }
public UIElement ContentElement
{
get { return (UIElement)GetValue(ContentElementProperty); }
set { SetValue(ContentElementProperty, value); }
}
public static readonly DependencyProperty ContentElementProperty = DependencyProperty.Register(
"ContentElement", typeof(UIElement), typeof(MyWindow),
new PropertyMetadata(null, (d, e) =>
{
MyWindow w = (MyWindow)d;
w.ContentBorder.Child = (UIElement)e.NewValue;
}));
public MyWindow() : base()
{
ToolBar = new ToolBar();
ToolBar.Height = 30;
ToolBar.VerticalAlignment = VerticalAlignment.Top;
StatusBar = new StatusBar();
StatusBar.Height = 20;
StatusBar.VerticalAlignment = VerticalAlignment.Bottom;
ContentBorder = new Border();
ContentBorder.SetValue(MarginProperty, new Thickness(0, 30, 0, 20));
Grid grid = new Grid();
grid.Children.Add(ToolBar);
grid.Children.Add(ContentBorder);
grid.Children.Add(StatusBar);
Content = grid;
}
}
}
使用 MyWindow 的 XAML 示例:
<local:MyWindow x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApplication1"
mc:Ignorable="d"
Title="MainWindow" Height="300" Width="300">
<Grid>
<Rectangle Fill="Blue" />
</Grid>
</local:MyWindow>
用UserControl 做同样的事情就很好,在设计器中也是如此。如果您想尝试,只需将每次出现的MyWindow 替换为MyUserControl 并从UserControl 扩展即可。
有什么方法可以让我像这样自定义Window 与设计师一起工作,还是我必须制作一个UserControl 并在每个窗口中使用它?
另外,这是某种错误还是预期行为?
附加信息:我正在运行 Visual Studio 2015 社区并且我正在使用 .net 4.6
我还尝试了另一种方法。我没有使用 ContentPropertyAttribute,而是像这样覆盖了 ContentProperty:
new public object Content {
get { return GetValue(ContentProperty); }
set { SetValue(ContentProperty, value); }
}
new public static DependencyProperty ContentProperty = DependencyProperty.Register("Content", typeof(object), typeof(BaseUserControl), new PropertyMetadata(null, (s, e) =>
{
MyWindow bw = (MyWindow)s;
bw.ContentBorder.Child = (UIElement)e.NewValue;
}));
这同样适用于UserControl。有了Window,我现在至少可以在设计器中看到内容,但是ToolBar 和StatusBar 仍然没有出现在设计器中。运行时一切正常。
【问题讨论】:
标签: c# wpf visual-studio designer