我创建了这个TinyWindow类,它派生自Window。
public class TinyWindow : Window
{
public TinyWindow()
{
Grid grid = new Grid();
grid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(50, GridUnitType.Pixel) });
grid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Star) });
ContentControl contentControl = new ContentControl();
contentControl.SetBinding(ContentControl.ContentProperty, new Binding(nameof(WindowContent)) { Source = this });
Grid.SetRow(contentControl, 1);
grid.Children.Add(contentControl);
Content = grid;
}
public object WindowContent
{
get { return (object)GetValue(WindowContentProperty); }
set { SetValue(WindowContentProperty, value); }
}
// Using a DependencyProperty as the backing store for WindowContent. This enables animation, styling, binding, etc...
public static readonly DependencyProperty WindowContentProperty =
DependencyProperty.Register("WindowContent", typeof(object), typeof(TinyWindow), new PropertyMetadata(null));
}
}
所以我可以在XAML中这样使用它。
<controls:TinyWindow x:Class="MyProject.Windows.SomeTinyWindow"
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:MyProject.Windows"
xmlns:controls="clr-namespace:MyProject.Controls"
mc:Ignorable="d"
Title="Select a Port">
<controls:TinyWindow.WindowContent>
<TextBlock Text="this is my content"/>
</controls:TinyWindow.WindowContent>
这很好。但我只想写这个就达到同样的效果。
<controls:TinyWindow x:Class="MyProject.Windows.SomeTinyWindow"
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:MyProject.Windows"
xmlns:controls="clr-namespace:MyProject.Controls"
mc:Ignorable="d"
Title="Select a Port">
<TextBlock Text="this is my content"/>
我怎么才能做到这一点?是否重写内容属性?我试过了,但基地。此处的内容为空。
public new object Content
{
get { return base.Content; }
set
{
var grid = base.Content as Grid;
//some logic to add value to gris
}
}
你有什么推荐的吗?
1条答案
按热度按时间r7xajy2e1#
不需要声明具有附加Content属性的派生Window类。只需声明一个Window
ControlTemplate
资源,e.g.应用。资源然后像这样使用它:
ControlTemplate也可以是Window
Style
资源的一部分。