XamlParseException. Ошибка в коде

178
17 февраля 2019, 15:00

Скажите как исправить ошибку

System.Windows.Markup.XamlParseException: ""Предоставление значения для "System.Windows.StaticResourceExtension" вызвало исключение.": номер строки "9" и позиция в строке "151"."

Внутреннее исключение. Exception: Не удается найти ресурс с именем "MyViewModel". Имена ресурсов определяются с учетом регистра.

App.xaml

<Application x:Class="COP.App"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:ModernButton="clr-namespace:ModernButton;assembly=ModernButton"
         xmlns:local="clr-namespace:COP"
         xmlns:local1="clr-namespace:COP.ViewModel">
<Application.Resources>
    <local1:MainViewModel x:Key="MyViewModel" />
</Application.Resources>

Window1.xaml

<Window
    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:COP"
    xmlns:ModernButton="clr-namespace:ModernButton;assembly=ModernButton" x:Class="COP.Window1"
    mc:Ignorable="d"
    Title="Window1" Height="700" Width="500" MinHeight="360" MinWidth="350" AllowsTransparency="True" Background="Transparent" WindowStyle="None" ResizeMode="CanResizeWithGrip" DataContext="{StaticResource MyViewModel}">
<Border Style="{StaticResource DefaultStyleBorder}">
    <Grid>
        <!--Top Panel-->
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"></RowDefinition>
            <RowDefinition Height="Auto"></RowDefinition>
            <RowDefinition Height="Auto"></RowDefinition>
            <RowDefinition Height="Auto"></RowDefinition>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"></ColumnDefinition>
            <ColumnDefinition Width="Auto"></ColumnDefinition>
            <ColumnDefinition Width="*"></ColumnDefinition>
        </Grid.ColumnDefinitions>
    <ModernButton:ModernBTN BtnText="Назад" Name="back" HorizontalAlignment="Left" CornerRadius="17,0,0,0" Style="{StaticResource DefaultButtonStyle}"/>
    <Frame Grid.Column="0" Grid.ColumnSpan="3" Grid.Row="1" Content="{Binding CurrentPage}" NavigationUIVisibility="Hidden" Opacity="{Binding FrameOpacity}"></Frame>
        <TextBlock Grid.Row="2" Grid.Column="1" Style="{StaticResource StyleTextBlock}">Регистрация</TextBlock>
        <TextBlock Grid.Row="3" Grid.Column="1" Style="{StaticResource StyleTextBlock}">Востановить пароль</TextBlock>
    </Grid>
</Border>

Могу выложить еще код если нужно будет. MainViewModel.cs

class MainViewModel : INotifyPropertyChanged
{
    ApplicationContext db;
    private Page Login;
    private Page Register;
    private DataBaseHelper helper;
    private MainWindow m;
    private Window1 n;
    private bool _lightStyle = true;
    public bool LightStyle
    {
        get { return _lightStyle; }
        set { _lightStyle = value; OnPropertyChanged(); }
    }
    private Page _currentPage;
    public Page CurrentPage
    {
        get { return _currentPage; }
        set { _currentPage = value; OnPropertyChanged(); }
    }
    private double _frameOpacity;
    public double FrameOpacity
    {
        get { return _frameOpacity; }
        set { _frameOpacity = value; OnPropertyChanged(); }
    }
    private string _loginValue = String.Empty;
    public string LoginValue
    {
        get { return _loginValue; }
        set { _loginValue = value; OnPropertyChanged(); }
    }
    public Commands.AuthCommand AuthCommand { get; set; }
    public MainViewModel()
    {
        helper = new DataBaseHelper();
        Login = new Pages.Login();
        Login.DataContext = this;
        Register = new Pages.Register();
        FrameOpacity = 1;
        CurrentPage = Login;
        LightStyle = false;
        this.AuthCommand = new Commands.AuthCommand(this);
    }
    public MainViewModel(Window1 window)
    {
        n = window;
        helper = new DataBaseHelper();
        Login = new Pages.Login();
        Login.DataContext = this;
        Register = new Pages.Register();
        FrameOpacity = 1;
        CurrentPage = Login;
        LightStyle = false;
    }
    public void AuthMethod(object parametr)
    {
        bool isExist = helper.LoginExist(LoginValue, ((PasswordBox)parametr).Password.ToString());
        if (isExist)
        {
            System.Windows.Forms.MessageBox.Show("Зарегестрирован уже");
            n.DialogResult = true;
        }
        else
            System.Windows.Forms.MessageBox.Show("Такого логина не существует!");
    }
    public ICommand ExitCommand
    {
        get { return new RelayCommand(o => { Environment.Exit(0); }); }
    }
    public async void SlowOpacity(string page)
    {
        await Task.Factory.StartNew(() =>
        {
            for (double i = 1.0; i > 0.0; i -= 0.1)
            {
                FrameOpacity = i;
                Thread.Sleep(50);
            }
            if (page == "Login")
                CurrentPage = Login;
            else
                CurrentPage = Register;
            for (double i = 0.0; i < 1.1; i += 0.1)
            {
                FrameOpacity = i;
                Thread.Sleep(50);
            }
        });
    }
    public event PropertyChangedEventHandler PropertyChanged;
    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

App.xaml.cs

public partial class App : Application
{
    protected override void OnStartup(StartupEventArgs e)
    {
        base.OnStartup(e);
        Window1 LoginWindow = new Window1();
        LoginWindow.ShowDialog();
        LoginWindow.DataContext = new ViewModel.MainViewModel();
        if(LoginWindow.DialogResult == true)
        {
            MainWindow mv = new MainWindow();
            mv.Show();
            LoginWindow.Close();
        }
    }
}
Answer 1

Можно указать ссылку на ресурс в окне.

<Window.Resources>
            <local1:MainViewModel x:Key="MyViewModel" />
</Window.Resources>
READ ALSO
Ресайз Bitmap в пропорции

Ресайз Bitmap в пропорции

Как правильнее ресайзить изображение в формате Bitmap, с учётом:

121
C# Кодирование строки посимвольно

C# Кодирование строки посимвольно

я не знаю, как каждый символ строки в цикле перекодировать в номер ASCII элементаИмеется str - строка english\russian букв

124