有没有推荐的WPF方法来创建一个在应用程序中使用的通用窗口样式?我有几个对话框出现在我的应用程序中,我希望它们的样式相同(相同的窗口边框,确定/取消按钮位置等),并根据情况简单地在每个中都有不同的"内容".因此,一个对话框中可能包含一个列表框,一个可能有一个文本框,依此类推.
我理解如何制作基本.cs用户控制文件,但是我不能为我的生活找到一个好方法来创建一个可以在启动时托管不同内容的窗口?
干杯,rJ
H.B*_*.B. 16
一种方法是使用新的自定义控件,我们称之为DialogShell:
namespace Test.Dialogs
{
public class DialogShell : Window
{
static DialogShell()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(DialogShell), new FrameworkPropertyMetadata(typeof(DialogShell)));
}
}
}
Run Code Online (Sandbox Code Playgroud)
现在需要一个通常定义的模板,在Themes/Generic.xaml那里你可以创建默认结构并绑定Content:
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:Test.Dialogs">
<Style TargetType="{x:Type local:DialogShell}" BasedOn="{StaticResource {x:Type Window}}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:DialogShell}">
<Grid Background="{TemplateBinding Background}">
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<!-- This ContentPresenter automatically binds to the Content of the Window -->
<ContentPresenter />
<StackPanel Grid.Row="1" Orientation="Horizontal" Margin="5" HorizontalAlignment="Right">
<Button Width="100" Content="OK" IsDefault="True" />
<Button Width="100" Content="Cancel" IsCancel="True" />
</StackPanel>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
Run Code Online (Sandbox Code Playgroud)
这只是一个例子,你可能想挂钩这些按钮与自定义事件,您需要在CS-文件中定义的属性.
然后可以像这样使用这个shell:
<diag:DialogShell x:Class="Test.Dialogs.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:diag="clr-namespace:Test.Dialogs"
Title="Window1" Height="300" Width="300">
<Grid>
<TextBlock Text="Lorem Ipsum" />
</Grid>
</diag:DialogShell>
Run Code Online (Sandbox Code Playgroud)
namespace Test.Dialogs
{
public partial class Window1 : DialogShell
{
public Window1()
{
InitializeComponent();
}
}
}
Run Code Online (Sandbox Code Playgroud)
事件接线示例(不确定这是否是"正确"方法)
<Button Name="PART_OKButton" Width="100" Content="OK" IsDefault="True" />
<Button Name="PART_CancelButton" Width="100" Content="Cancel" IsCancel="True" />
Run Code Online (Sandbox Code Playgroud)
namespace Test.Dialogs
{
[TemplatePart(Name = "PART_OKButton", Type = typeof(Button))]
[TemplatePart(Name = "PART_CancelButton", Type = typeof(Button))]
public class DialogShell : Window
{
//...
public DialogShell()
{
Loaded += (_, __) =>
{
var okButton = (Button)Template.FindName("PART_OKButton", this);
var cancelButton = (Button)Template.FindName("PART_CancelButton", this);
okButton.Click += (s, e) => DialogResult = true;
cancelButton.Click += (s, e) => DialogResult = false;
};
}
}
}
Run Code Online (Sandbox Code Playgroud)