Reputation: 911
I am trying to use generic windows in WPF. I know how to create them, but I have hard time specify resources or anything else in the root element in such a 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. I am missing something here?
This is a minimal (non)functional code:
MainWIndow.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
public partial class MainWindow : ViewBase<TestViewModel>
{
public MainWindow()
: base(null)
{
InitializeComponent();
}
public MainWindow(TestViewModel vm)
: base(vm)
{
InitializeComponent();
}
}
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()
{
}
}
Upvotes: 0
Views: 244
Reputation: 128013
Just write 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>
Upvotes: 1