簡體   English   中英

不能把窗口放在一個樣式(WPF)

[英]Can't put a window in a style (WPF)

我覺得我錯過了一些非常重要的東西。 我創建了以下代碼:

文件:App.xaml

<Application x:Class="HelloWorld.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             Startup="Application_Startup">
    <Application.Resources>

        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="MainView.xaml" />
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>

    </Application.Resources>
</Application>

文件:MainWindow.xaml

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:viewmodel="clr-namespace:HelloWorld.ViewModel">
    <DataTemplate DataType="{x:Type viewmodel:ViewModel}">
        <Window Title="HelloWorld">
            <Window.Resources>
                <Style TargetType="TextBlock">
                    <Setter Property="Margin" Value="50"></Setter>
                </Style>
            </Window.Resources>
            <TextBlock Text="TODO" />
        </Window>
    </DataTemplate>
</ResourceDictionary>

雖然我可以編譯代碼,但一切看起來都不錯。 我從<Window Title="HelloWorld"></Window>得到灰色的搖擺線,並帶有“無法將窗口置於樣式中”的消息。 我想知道我做錯了什么?

我該怎么做才能改進我的代碼? 我正在嘗試使用MVVM。

謝謝!

Window

提供創建,配置,顯示和管理窗口和對話框生命周期的功能。

和:

主要用於顯示獨立應用程序的窗口和對話框。

由於Window元素是頂級元素,因此無法將它們添加到較低級別元素的Content中。 不能把一個窗口放在一個樣式錯誤是明確的...你不能在一個Style使用一個Window ,或在你的情況下使用DataTemplate

而不是嘗試,你有幾個選擇:

1)將Window內容放入DataTemplate ,然后在Window中的ContentControl中顯示該內容:

<DataTemplate DataType="{x:Type viewmodel:ViewModel}">
    <!-- Define content -->
</DataTemplate>

...

<ContentControl Content="{Binding ViewModelProperty}" />

2)使用UserControl而不是Window元素:

<DataTemplate DataType="{x:Type viewmodel:ViewModel}">
    <UserControl>
        <!-- Define Content here -->
    </UserControl>
</DataTemplate>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM