添加样式后抛出异常

时间:2018-05-09 14:45:51

标签: c# wpf data-binding

我正在尝试为我的应用程序添加全局样式。将该部分添加到我的App.xaml后,我得到一个令人困惑的运行时异常:

  

发生了'System.IO.IOException'类型的未处理异常   PresentationFramework.dll无法找到资源   '视图/视图/ createjob.xaml'。

在设计时,我可以看到我的样式在Visual Studio的设计/预览面板中正确应用。

我在网上看到的大多数示例都显示了在样式上设置的Key属性,然后由使用它的每个Window显式引用。我正在寻找一些全局的东西,即我不需要通过我的代码库并且每次都明确地引用该样式。

完整App.xaml

<Application x:Class="TestApp.Views.App"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:local="clr-namespace:TestApp"
         StartupUri="Views/CreateJob.xaml">
<Application.Resources>
    <Style TargetType="{x:Type TextBox}">
        <Setter Property="VerticalContentAlignment" Value="Center"/>
    </Style>
</Application.Resources>

完整的CreateJob.xaml

<Window x:Class="TestApp.Views.CreateJob"
    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:TestApp"
    mc:Ignorable="d"
    Title="CreateJob" Height="450" Width="800">
<StackPanel Orientation="Horizontal">
    <Label Content="Name"/>
    <TextBox/>
</StackPanel>

完整的CreateJob.xaml.cs

using System.Windows;

namespace TestApp.Views
{
    /// <summary>
    /// Interaction logic for CreateJob.xaml
    /// </summary>
    public partial class CreateJob : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
    }
}

完整的App.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
    </startup>
</configuration>

1 个答案:

答案 0 :(得分:0)

根据您提供的代码,您正在寻找错误的资源。

您正在寻找Views/CreateJob.xaml,但您正在向我们MainWindow.xaml提供“CreateJob”标题。资源uri正在查找实际文件名而不是标题。像这样更新它,它会工作。

StartupUri="Views/MainWindow.xaml"