Vâng, tôi đã có thể làm cho công việc này theo cách sau:
Trong máy chủ ứng dụng WPF của tôi, tôi đã thêm Import này:
[ImportMany("ApplicationResources", typeof(ResourceDictionary))]
public IEnumerable<ResourceDictionary> Views { get; set; }
Sau đó, trong phần tổng hợp của tôi, tôi tuyên bố một ViewModel và một mẫu dữ liệu cho ViewModel trong một tệp ResourceDictionary Xaml thông thường. Sau đó, tôi tạo ra một mã số đằng sau cho ResourceDictionary, như thế này (trong ví dụ này, các ViewModel được gọi ItemViewModel và ResourceDictionary được gọi ItemView):
[Export("ApplicationResources", typeof(ResourceDictionary))]
public partial class ItemView : ResourceDictionary
{
public ItemView()
{
InitializeComponent();
}
}
Để tham khảo, các XAML ví dụ như ResourceDictionary trông như thế này:
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:MyCompany.MyProduct"
x:Class="MyCompany.MyProduct.ItemView">
<DataTemplate DataType="{x:Type local:ItemViewModel}">
...
</DataTemplate>
</ResourceDictionary>
sau đó, trở lại trong máy chủ ứng dụng WPF của tôi, sau khi tôi soạn thành công và trước khi tôi hiển thị cửa sổ chính, tôi làm điều này:
// Add the imported resource dictionaries
// to the application resources
foreach (ResourceDictionary r in Views)
{
this.Resources.MergedDictionaries.Add(r);
}
Điều đó dường như áp dụng thành công DataTemplate ở bất cứ đâu WPF thấy một ItemViewModel.
EDIT: Đối với bất kỳ ai quan tâm, tôi đã phát hành một khung ứng dụng được gọi là SoapBox Core làm nguồn mở và sử dụng rộng rãi phương pháp này để nhập Chế độ xem vào tài nguyên ứng dụng. Nó hoạt động rất tốt, và bạn có thể tự tải xuống nguồn và xem cách nó hoạt động.
Tôi đã thử cách tiếp cận chính xác này nhưng ResourceDictionary trống khi tải. Có cách nào để bắt buộc hoặc tôi đang làm điều gì sai? –