简体   繁体   English

通用 wpf window 中的资源

[英]Resources in generic wpf window

I am trying to use generic windows in WPF.我正在尝试在 WPF 中使用通用 windows。 I know how to create them, but I have hard time specify resources or anything else in the root element in such a window.我知道如何创建它们,但我很难在 window 的根元素中指定资源或其他任何内容。 Is this possible?这可能吗? You can use x:TypeArguments only in the root tag, so I am afraid that any definition outside of the root tag won't get recognized and handled without generic specification.您只能在根标记中使用 x:TypeArguments ,所以恐怕根标记之外的任何定义在没有通用规范的情况下都不会被识别和处理。 I am missing something here?我在这里遗漏了什么?

This is a minimal (non)functional code:这是一个最小(非)功能代码:

MainWIndow.xaml主窗口.xaml

<local:ViewBase x:Class="WpfApp1.MainWindow"
            x:TypeArguments="local:TestViewModel"
            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:WpfApp1"
            mc:Ignorable="d"
            Title="MainWindow" Height="450" Width="800">

<local:ViewBase.Resources>
    <ResourceDictionary>
        <Style x:Key="TEST" TargetType="TextBlock">
            <Setter Property="Foreground" Value="Red"/>
        </Style>
    </ResourceDictionary>
</local:ViewBase.Resources>

<Grid>
    <TextBlock Text="TEST" Style="{StaticResource TEST}" />
</Grid>

MainWindow.xaml.cs主窗口.xaml.cs

public partial class MainWindow : ViewBase<TestViewModel>
{
    public MainWindow()
        : base(null)
    {
        InitializeComponent();
    }

    public MainWindow(TestViewModel vm)
        : base(vm)
    {
        InitializeComponent();
    }
}

SomeClass.cs SomeClass.cs

public class ViewBase<T> : Window where T : ViewModelBase
{
    public ViewBase(T vm)
    {
        DataContext = vm;
    }
}

public class ViewModelBase
{
    public ViewModelBase()
    {

    }
}

public class TestViewModel : ViewModelBase
{
    public TestViewModel()
    {

    }
}

Just write Window.Resources :只需写Window.Resources

<local:ViewBase ...>
    <Window.Resources>
        <ResourceDictionary>
            <Style x:Key="TEST" TargetType="TextBlock">
                <Setter Property="Foreground" Value="Red"/>
            </Style>
        </ResourceDictionary>
    </Window.Resources>
    <Grid>
        <TextBlock Text="TEST" Style="{StaticResource TEST}" />
    </Grid>
</local:ViewBase>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM