Martyn Ball
Martyn Ball

Reputation: 4885

Access XAML Instance of Class from Code Behind

I used to have an instance of a custom class define in app.xaml.cs so I could access it anywhere in my application. How ever I have now changed that so that an instance of my class is made within my Application Resources.

App.xaml

<Application x:Class="Duplicate_Deleter.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:Duplicate_Deleter">
    <Application.Resources>
        <local:runtimeObject x:Key="runtimeVariables" />
    </Application.Resources>
</Application>

App.xaml.cs This is the class.

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;

namespace Duplicate_Deleter
    /// <summary>
    /// Global values for use during application runtime
    /// </summary>
    public class runtimeObject
    {
        //Can the application be closed?
        private bool _inProgress = false;
        public bool inProgress
        {
            get { return _inProgress; }
            set { _inProgress = value; }
        }

        //Selected folder to search in
        private string _fromFolder = "testing string";
        public string fromFolder
        {
            get { return _fromFolder; }
            set { _fromFolder = value; }
        }
    }
}

My problem is now, I need to be able to access this instance of the class within my code behind in my commands namespace. Below you can see one of the commands, the App.runtime used to work when the instance was within App.xaml.cs.

Classes > Commands.cs

public static void CloseWindow_CanExecute(object sender,
                           CanExecuteRoutedEventArgs e)
        {
            if (App.runtime.inProgress == true)
            {
                e.CanExecute = false;
            }
            else
            {
                e.CanExecute = true;
            }
        }

How do I now reference my class instance from within my commands?

Upvotes: 1

Views: 1654

Answers (1)

kkyr
kkyr

Reputation: 3845

You can use TryFindResource anywhere in code:

public static void CloseWindow_CanExecute(object sender,
                       CanExecuteRoutedEventArgs e)
    {
        // Find the resource, then cast it to a runtimeObject
        var runtime = (runtimeObject)Application.Current.TryFindResource("runtimeVariables");

        if (runtime.InProgress == true)
        {
            e.CanExecute = false;
        }
        else
        {
            e.CanExecute = true;
        }
    }

If the resource is not found it will return null. You could add null checking to avoid an InvalidCastException.

Upvotes: 2

Related Questions