gpt4 book ai didi

wpf - 如何创建通用的WPF基础窗口样式?

转载 作者:行者123 更新时间:2023-12-03 07:36:44 25 4
gpt4 key购买 nike

是否有任何推荐的方式使用 WPF 创建跨应用程序使用的通用窗口样式?我的应用程序中出现了几个对话框,我希望它们的样式都相同(相同的窗口边框、确定/取消按钮位置等),并且根据具体情况,每个对话框都有不同的“内容”。因此,一个对话框中可能有一个列表框,一个对话框中可能有一个文本框,等等。

我了解如何制作基本的 .cs 用户控件文件,但我一生都无法找到一种好方法来创建一个在启动时可以托管不同内容的单个窗口?

干杯,rJ

最佳答案

一种方法是创建一个新的自定义控件,我们将其称为 DialogShell:

namespace Test.Dialogs
{
public class DialogShell : Window
{
static DialogShell()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(DialogShell), new FrameworkPropertyMetadata(typeof(DialogShell)));
}
}
}

现在需要一个通常在 Themes/Generic.xaml 中定义的模板,您可以在其中创建默认结构并绑定(bind)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>

这只是一个示例,您可能希望将这些按钮与需要在 cs 文件中定义的自定义事件和属性 Hook 。

这个 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>
namespace Test.Dialogs
{
public partial class Window1 : DialogShell
{
public Window1()
{
InitializeComponent();
}
}
}
<小时/>

事件接线示例(但不确定这是否是“正确”的方法)

<Button Name="PART_OKButton" Width="100" Content="OK" IsDefault="True" />
<Button Name="PART_CancelButton" Width="100" Content="Cancel" IsCancel="True" />
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;
};
}
}
}

关于wpf - 如何创建通用的WPF基础窗口样式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7507953/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com