尝试重复使用WPF窗口

3
下面的XAML用于一个窗口,我在几个演示中使用它,唯一变化的是它所托管的UserControl:
    <Window x:Class="Smack.ConstructionAdmin.Presentation.Wpf.Views.Admin.Employees.EmployeeShellView"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
        xmlns:local="clr-namespace:Smack.ConstructionAdmin.Presentation.Wpf.Views.Admin.Employees" 
        xmlns:s="clr-namespace:Smack.ConstructionAdmin.Presentation.Wpf" 
        xmlns:cmdRef="clr-namespace:Smack.Core.Presentation.Wpf.ViewModels.Commands.Reference;assembly=Smack.Core.Presentation.Wpf" 

        Background="{DynamicResource WaveWindowBackground}"
        Title="{Binding Source={x:Static s:Strings.AppName}}"  
        Icon="pack://application:,,,/Smack.ConstructionAdmin.Presentation.Wpf;component/Images/Time-Machine_16.png"
        FontFamily="Arial"  
        WindowStartupLocation="CenterScreen" Width="750" Height="600" 
        >
    <DockPanel>
        <local:EmployeeShellUserControl DataContext="{Binding}"  />
    </DockPanel>

    <Window.InputBindings>
        <cmdRef:KeyBindingEx  CommandReference="{Binding AddCommand}"/>
        <cmdRef:KeyBindingEx  CommandReference="{Binding EditCommand}"/>
        <cmdRef:KeyBindingEx  CommandReference="{Binding DeleteCommand}"/>
    </Window.InputBindings>

</Window>

看起来,重复使用某些不会变化的部分是有道理的。以下是我第一次尝试使用样式表:

<Style x:Key="MyWindowStyle" TargetType="{x:Type Window}">
    <Setter Property="Background" Value="{DynamicResource WaveWindowBackground}"></Setter>
    <Setter Property="FontFamily" Value="Arial"></Setter>
    <Setter Property="Height" Value="600"></Setter>
    <Setter Property="Width" Value="750"></Setter>
    <Setter Property="Title" Value="{Binding AppName}"></Setter>
    <Setter Property="Icon" Value="{Binding IconUri}"></Setter>
</Style>

痛点

  1. 我找不到WindowStartupLocation的属性设置器
  2. 我不知道如何将InputBindings作为样式的一部分

使用样式是正确的方法吗?还是我需要使用其他技术?如何设置上述属性?

谢谢。
Berryl

2个回答

4
为什么不直接创建一个没有内容的这种类型的窗口,然后在显示它之前将您选择的UserControl添加为其Content?您将不需要多个Window子类,也不需要混乱的样式。
以下是一个简单的示例,我们将窗口的内容设置为一个字符串(通常您会使用一些适当的UserControl):
var window = new EmployeeShellView();
window.Content = "Hello world!"; // set to your UserControl
window.Show();

如果您想插入一个复杂的UserControl,比如这个:

<UserControl x:Class="MyControl">
    <DockPanel>
        <local:EmployeeShellUserControl DataContext="{Binding}"  />
    </DockPanel>
</UserControl>

你将需要做:

var window = new EmployeeShellView();
window.Content = new MyControl();
window.Show();

听起来很完美!但是我不确定你的意思 - 你能写一些代码和/或XAML来更好地说明吗? - Berryl
@Berryl:我已经添加了一个示例,看起来还可以吗? - Jon
那么保留ShellView不变,实例化它并设置Content?我替换现有的UserControl成为Content的部分是如何进行的,或者这就是Content属性的定义吗? - Berryl
我在文档中没有看到关于窗口内容的信息。那是一个标准属性而我错过了还是你们正在添加一个占位符?我还没有理解那一部分。 - Berryl
@Berryl:它是ContentControl.Content——Window派生自ContentControl - Jon
哦,太棒了。我也可以设置DataContext。那么我发布的现有UserControl就是那个窗口的内容,是吗?太简单了,太酷了 - 谢谢! - Berryl

0

我建议您通过设置样式中的附加行为来解决问题。

只需在Google上搜索“wpf附加行为”即可。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接