我创建了这个派生自 Window 的 TinyWindow 类。
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 >
效果很好。但我想只写这个来达到同样的结果。
<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"/>
</controls:TinyWindow>
我怎样才能做到这一点?覆盖内容属性?我试过了,但是 base.Content 在这里是空的。
public new object Content
{
get { return base.Content; }
set
{
var grid = base.Content as Grid;
//some logic to add value to gris
}
}
你有什么建议?
您不需要声明具有附加 Content 属性的派生 Window 类。只需声明一个窗口
ControlTemplate
,例如在 Application.Resources
<ControlTemplate x:Key="TinyWindowTemplate" TargetType="Window">
<Grid Background="{TemplateBinding Background}">
<Grid.RowDefinitions>
<RowDefinition Height="50"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<ContentControl Grid.Row="1" Content="{TemplateBinding Content}"/>
</Grid>
</ControlTemplate>
并像这样使用它:
<Window ... Template="{StaticResource TinyWindowTemplate}">
<TextBlock Text="this is my content"/>
</Window>
ControlTemplate 也可以是 Window
Style
资源的一部分。