Changing Controls from anywhere - c#

What I want to do:
I want do change a background color of a button from anywhere in my code (other classes Xamarin Forms). For example a button A in Page A changes the color of button B in Page B
on Windows you can use the MethodInvoker Delegat which isn't available on Android/iOS.
Can you give me a hint?
I tried it with the text of the buttons before with the MVVM approach.
in my PageB.xaml:
<Button Name="Button_B" Text="{Binding MyText}"/>
in my PageB.cs in public PageB
BindingContext = new MVVMPageB();
in my MVVMPageB.cs
private string myText;
public string MyText
{
get => mytring;
set
{
mystring = value;
PropertyChanged?
.Invoke(this, new PropertyChangedEventArgs(MyText)));
}
if i call:
MyText("Test");
in my MVVMPageB.cs it works fine. but i dont know how to access this from anywhere else.
i tried:
var Testobjekt = new MVVMPageB() //pretty sure thats not correct
Testobjekt.MyText("Test"); //wont work

Technique 1
This is a Singleton pattern for MVVMPageB.
This works if you never have two "Page B"s. IF there is a Page B on the navigation stack (so you can "Go Back" to it), and you display ANOTHER Page B, THEN this will not work well, because both Page B's will refer to the SAME MVVMPageB instance.
public class MVVMPageB : ...
{
// "Singleton": This is the only instance of MVVMPageB.
private static MVVMPageB _It;
public static MVVMPageB It
{
if (_It == null)
_It = new MVVMPageB();
return _It;
}
// Your constructor.
// It is private; only used via "It" getter above.
private MVVMPageB()
{
...
}
}
Code in another class, to access a member of the MVVMPageB.
MVVMPageB.It.MyText("Test");
Replace this code:
BindingContext = new MVVMPageB();
With this code:
BindingContext = MVVMPageB.It;
NOTE: Because MVVMPageB.It is static, if you go to Page B a second time, it will show the values you had last time (within the same app session).
Technique 2
A more robust approach, which works even if you create another Page B, requires having some way to pass the current instance of MVVMPageB to MVVMPageA or to PageA.
A complete example depends on exactly how/where you create each page. But this shows the idea.
public class MVVMPageB : ...
{
// Your constructor. Add parameters as needed.
public MVVMPageB()
{
...
}
}
public partial class PageB : ...
{
// Convenience property - our BindingContext is type MVVMPageB.
public MVVMPageB VMb => (MVVMPageB)BindingContext;
...
}
public class MVVMPageA : ...
{
// This is here, so both MVVMPageA and PageA can find it.
public MVVMPageB VMb;
}
public partial class PageA : ...
{
// Convenience property - our BindingContext is type MVVMPageA.
public MVVMPageA VMa => (MVVMPageA)BindingContext;
...
}
Code that creates Page B and then Page A:
var pageB = new PageB();
var pageA = new PageA();
// Tell MVVMPageA about MVVMPageB.
pageA.VMa.VMb = pageB.VMb;
Methods in MVVMPageA can now access members of MVVMPageB:
VMb.MyText("Test");
Methods in PageA can now access members of MVVMPageB:
VMa.VMb.MyText("Test");
NOTE: In this dynamic technique, if you go to Page B a second time (in the same app session), it will have a new instance of MVVMPageB.

You need a singleton viewModel for this use. I usually use one for the navbar.
So every scoped page viewModel references the singleton global viewModel inside:
PageAViewModel has property NavBarModel
PageBViewModel has property NavBarModel
and so on..
So it's obvious your button will be bind as
BackgroundColor={Binding NavBarModel.ActionColor} on every different page.
Now to have a singleton and obtain its reference i can see two ways: dependency injection (DI) or single instance creation. You can read a lot about DI on the net, while for a simple case you can have a single instance model with a prop like:
private NavBarModel _current;
public NavBarModel Current
{
get
{
if (_current == null)
_current = new NavBarModel();
return _current;
}
}
then in pages viewModels constructor set NavBarModel = NavBarModel.Current;
You would need DI though to reference more models inside your singleton, or/and make your code more reusable. Good luck.

Related

How to access a custom control dependency propery from its viewmodel

I'm working on a multiple document viewer (a simple window with a custom control, each with a separate viewmodel). When clicking on a filename, a new instance of the user control is added to the main window. The user control has a dependency property which holds the path to the filename, defined in it's code-behind. Now i'm struck on how to get the value of this property from the user control to the viewmodel, so it can show the actual document. Any Hints?
<ctrl:DocViewerControl x:Key="docviewer" DocumentSource="{Binding SelectedItem.Path, ElementName=docList}"/>
I use this code in main window to make new instances of my user control where DocumentSource is the dependency property i need access to, as stated above.
Edit:
Following is the (relevant) code for the view and the viewmodel of my control, specific to the dependancy property value capture problem i have.
UserControl.xaml.cs
public partial class ToolboxControl : UserControl
{
public static readonly DependencyProperty DocumentSourceProperty = DependencyProperty.Register("DocumentSource",
typeof(string), typeof(ToolboxControl), new UIPropertyMetadata(new PropertyChangedCallback(OnDocumentSourceChanged)));
public ToolboxControl()
{
InitializeComponent();
}
public string DocumentSource
{
get { return (string)GetValue(DocumentSourceProperty); }
set { SetValue(DocumentSourceProperty, value); }
}
private static void OnDocumentSourceChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
}
}
PV_ViewModel.cs
public class PV_ViewModel : ObservableObject
{
.....
public string DocumentSource
{
get { return (String.IsNullOrEmpty(_documentsource)? (_documentsource = #"about:blank") : _documentsource); }
set { SetField<string>(ref _documentsource, value, "DocumentSource"); }
}
.....
public PV_ViewModel()
{
PropertyChanged += DocumentSourceChanged;
}
.....
protected void DocumentSourceChanged(object sender, PropertyChangedEventArgs e)
{
if (sender != null)
{
switch(e.PropertyName)
{
case "DocumentSource":
{
// show the document and whatsoever
break;
}
}
}
}
.....
}
Neither the getter nor the setter of the viewmodel DocumentSource property get accessed from anywhere, despite the UserControl in MainWindow had is DocumentSourceProperty filled in with the current document path string. (i can see it form a collection of currently opened document on the main app).
To clarify: the application solution contains MainWindow project (the main view, a simple window with a TreeView and the UserControl container), the UserControl project (the (hopefully) standalone application used to show a single document when providing the path to the doc to show through the DocumentSource property.
I am not really sure I understand your problem (or if you understand how Dependency Properties work), so you may have to post a bit more of your code behind (with the DI for example)
Typically your DocViewerControl looks like this
public abstract class DocViewerControl : UserControl
{
public string Path
{
get { return (string)GetValue(PathProperty); }
set { SetValue(PathProperty, value); }
}
public static readonly DependencyProperty PathProperty =
DependencyProperty.Register("Path", typeof(string), typeof(DocViewerControl), new PropertyMetadata(string.Empty));
}
This will expose a Property in XAML of the control.
It's important here that you make it TwoWay binding, so any change from the UserControll will update the bounded field in your ViewModel.
Your ViewModel:
public class Doc1ViewModel : ViewModelBase {
private string path;
public string Path
{
get { return path;}
set {
if(path!=value) {
path = value;
OnPropertyChanged("Path");
}
}
}
}
Now, each time when you assign the property in your UserControl, the value in the ViewModel will be updated. As you can see, the Dependency Property consists from two properties. One static Dependency Property called PathProperty and one instance property called Path.
But having a closer look at it, it's not a real instance property at all. It just wraps calls around the Dependency Property by using GetValue and SetValue (which are derived from DependencyObject class, which every UI control inherits).
Hope this clears it up how Dependency Properties work, as it hard to tell what's wrong with your approach without seeing the code used.
In a nutshell, Dependency Properties (together with Attached Properties) extend the XAML code with TwoWay bindable properties (normal instance property can only be bound in one direction).

Creating global collection and accessing it from all pages (C# Windows)

I want to have a global collection which I can access/edit on any page i.e SpenderList.
Here I have the instance of a ObservableCollection created in App.xaml.cs:
namespace v003
{
public sealed partial class App : Application
{
public ObservableCollection<Spender> SpenderList = new ObservableCollection<Spender>();
public App()
{
this.InitializeComponent();
this.Suspending += this.OnSuspending;
}
...
}
}
When I type SpenderList on a page (MainPage.xaml.cs), the intellisense doesn't show that collection.
How do I access this collection from MainPage.xaml.cs and other pages?
Note: When I declared that instance in the MainPage.xaml.cs, all my subsequent codes work, so there's no issue with custom class, Spender.
Also I would like your opinion on this way of designing the app. Essentially all tasks are based on the items in this collection, and I'd want to any changes to this collection and its items performed from any page to be global.
you need to cast:
((App)Application.Current).SpenderList
or make it static:
public static ObservableCollection<Spender> SpenderList = new ObservableCollection<Spender>();
then you access it like this:
App.SpenderList
Generally you should try to avoid globally accessible static variables.

Modifying ViewModel Properties outside of ViewModel - Values aren't saving

Is it possible to modify properties of a ViewModel by using an instance of ViewModelLocator elsewhere in the code? When I try, any value I try to assign seems to be discarded.
For example, a ViewModel, an instance of which named "Game" is contained in my ViewModelLocator. It has a string property named "Test". When I try to modify it this way:
(App.Current.Resources["Locator"] as ViewModelLocator).Game.Test = "Testing";
System.Windows.MessageBox.Show((App.Current.Resources["Locator"] as ViewModelLocator).Game.Test);
or
ViewModelLocator _viewModelLocator = new ViewModelLocator();
_viewModelLocator.Game.Test = "Testing";
System.Windows.MessageBox.Show(_viewModelLocator.Game.Test);
The messageboxes display the value of the string declared in the ViewModel itself if there is one. If a value hasn't been assigned in the ViewModel, the messageboxes show up empty. Either way, they don't display "Testing".
How can I make this work? I'm using MVVM Light with Unity.
public class ViewModelLocator
{
private static Bootstrapper _bootstrapper;
static ViewModelLocator()
{
if (_bootstrapper == null)
_bootstrapper = new Bootstrapper();
}
public GameViewModel Game
{
get { return _bootstrapper.Container.Resolve<GameViewModel>(); }
}
}
public class Bootstrapper
{
public IUnityContainer Container { get; set; }
public Bootstrapper()
{
Container = new UnityContainer();
ConfigureContainer();
}
private void ConfigureContainer()
{
Container.RegisterType<GameViewModel>();
}
}
It looks like this is a problem with Unity. I switched back to MVVM Light's SimpleIoc and it works without a hitch.
When you call Container.RegisterType<GameViewModel>(); this registers the type GameViewModel with the default lifetime manager. The default lifetime manager for the RegisterType method is the TransientLifetimeManager which means that every time Resolve is called a new instance is returned.
So every time the Game property is called a new instance of GameViewModel is returned. Any modifications to the object will only be made to that object (and lost when the object is GC'd). The next time the Game property is called a new instance of GameViewModel is returned.
So, assuming you only want one GameViewModel you should register it as a singleton:
private void ConfigureContainer()
{
Container.RegisterType<GameViewModel>(new ContainerControlledLifetimeManager());
}

Windows Forms, Designer, and Singleton

I'm trying to work with Windows Forms and User Controls and thus far it's been nothing but a headache. I can't make the form or the controls static because the designer doesn't like that and when I use Singleton on my form and controls, the designer still throws errors at me.
My FormMain:
public partial class FormMain : Form
{
private static FormMain inst;
public static FormMain Instance
{
get
{
if (inst == null || inst.IsDisposed)
inst = new FormMain();
return inst;
}
}
private FormMain()
{
inst = this;
InitializeComponent();
}
MainScreen.cs:
public partial class MainScreen : UserControl
{
private static MainScreen inst;
public static MainScreen Instance
{
get
{
if (inst == null || inst.IsDisposed)
inst = new MainScreen();
return inst;
}
}
private MainScreen()
{
inst = this;
InitializeComponent();
}
If the constructor of MainScreen is public the program runs, but when I change it to private I now get an error in FormMain.Designer.cs saying "'Adventurers_of_Wintercrest.UserControls.MainScreen.MainScreen()' is inaccessible due to its protection level". It points to this line:
this.controlMainScreen = new Adventurers_of_Wintercrest.UserControls.MainScreen();
I think this is the instance of the class that the designer makes by default. Should I ditch the designer? Or is there a way around this? Or is there another way to make class properties accessible without using Singleton (since I can't seem to make the form or controls static)? Any help would be greatly appreciated.
You need to keep a reference to each instance of each form if you want to access the public properties of the instantiated form.
One way is to have a class with a static variable for each type of form:
class FormReferenceHolder
{
public static Form1 form1;
public static Form2 form2;
}
This way you would set the static variable whenever you instantiate a form, and then you can access that variable from anywhere in the program. You can go one step further with this and use properties that set up the form if it doesn't already exist:
class FormReferenceHolder
{
private static Form1 form1;
public static Form1 Form1
{
get
{
if (form1 == null) form1 = new Form1();
return form1 ;
}
}
}
...
static void Main()
{
Application.Run(FormReferenceHolder.Form1 );
}
I think I answered a previous question about this, which looks like it is what got you started down this route. The first point is that I wasn't recommending this pattern specifically, just trying to teach you more about how software developers can manage scope.
That said, the problem you are facing isn't insurmountable. You could hobble a public constructor by throwing an exception at runtime and not at design time, for instance, and modify Program.cs to use the static Instance instead of manually constructing the form.
But.
As I said in the other question, the better option would be to change architecture so that you don't need your library code to directly manipulate the GUI in the first place.
You can do this either by just having the GUI ask the library questions when it thinks it needs new data (simple functions) or by letting the GUI be notified when something needs to change. Either method would be better than having the library fiddle with labels directly.
A good place to start would be something like an MVC (model-view-controller) architecture, which I was alluding to in my previous answer. It might be best, though, to give us an idea of what your high-level program structure looks like now on a bit more detail. What are the main classes you are using in your system (not just the ones you've mentioned so far)? What is the main responsibility of each, and where does each live? Then our recommendations could be a little more specific.
EDIT
So, I have mocked up a quick demo of a possible alternative architecture, based on your comment.
I have the following in my project:
FormMain (Form)
TitleScreen (UserControl)
InGameMenu (UserControl)
MainScreen (UserControl)
GameController (Class)
GameModel (Class)
I didn't use Date and LoadSave, for now.
FormMain simply has an instance of each UserControl dropped on it. No special code.
GameController is a singleton (since you tried to use this pattern already and I think it would be helpful for you to try using a working version of it) that responds to user input by manipulating the model. Note well: you don't manipulate the model directly from your GUI (which is the View part of model-view-controller). It exposes an instance of GameModel and has a bunch of methods that let you perform game actions like loading/saving, ending a turn, etc.
GameModel is where all your game state is stored. In this case, that's just a Date and a turn counter (as if this were going to be a turn-based game). The date is a string (in my game world, dates are presented in the format "Eschaton 23, 3834.4"), and each turn is a day.
TitleScreen and InGameMenu each just have one button, for clarity. In theory (not implementation), TitleScreen lets you start a new game and InGameMenu lets you load an existing one.
So with the introductions out of the way, here's the code.
GameModel:
public class GameModel
{
string displayDate = "Eschaton 23, 3834.4 (default value for illustration, never actually used)";
public GameModel()
{
// Initialize to 0 and then increment immediately. This is a hack to start on turn 1 and to have the game
// date be initialized to day 1.
incrementableDayNumber = 0;
IncrementDate();
}
public void PretendToLoadAGame(string gameDate)
{
DisplayDate = gameDate;
incrementableDayNumber = 1;
}
public string DisplayDate
{
get { return displayDate; }
set
{
// set the internal value
displayDate = value;
// notify the View of the change in Date
if (DateChanged != null)
DateChanged(this, EventArgs.Empty);
}
}
public event EventHandler DateChanged;
// use similar techniques to handle other properties, like
int incrementableDayNumber;
public void IncrementDate()
{
incrementableDayNumber++;
DisplayDate = "Eschaton " + incrementableDayNumber + ", 9994.9 (from turn end)";
}
}
Things to note: your model has an event (in this case, just one of type EventHandler; you could create more expressive types of events later, but let's start simple) called DateChanged. This will be fired whenever DisplayDate changes. You can see how that happens when you look at the property definition: the set accessor (which you will NOT call from your GUI) raises the event if anyone is listening. There are also internal fields to store game state and methods which GameController (not your GUI) will call as required.
GameController looks like this:
public class GameController
{
private static GameController instance;
public static GameController Instance
{
get
{
if (instance == null)
instance = new GameController();
return instance;
}
}
private GameController()
{
Model = new GameModel();
}
public void LoadSavedGame(string file)
{
// set all the state as saved from file. Since this could involve initialization
// code that could be shared with LoadNewGame, for instance, you could move this logic
// to a method on the model. Lots of options, as usual in software development.
Model.PretendToLoadAGame("Eschaton 93, 9776.9 (Debug: LoadSavedGame)");
}
public void LoadNewGame()
{
Model.PretendToLoadAGame("Eschaton 12, 9772.3 (Debug: LoadNewGame)");
}
public void SaveGame()
{
// to do
}
// Increment the date
public void EndTurn()
{
Model.IncrementDate();
}
public GameModel Model
{
get;
private set;
}
}
At the top you see the singleton implementation. Then comes the constructor, which makes sure there's always a model around, and methods to load and save games. (In this case I don't change the instance of GameModel even when a new game is loaded. The reason is that GameModel has events and I don't want listeners to have to unwire and rewire them in this simple sample code. You can decide how you want to approach this on your own.) Notice that these methods basically implement all the high-level actions your GUI might need to perform on the game state: load or save a game, end a turn, etc.
Now the rest is easy.
TitleScreen:
public partial class TitleScreen : UserControl
{
public TitleScreen()
{
InitializeComponent();
}
private void btnLoadNew(object sender, EventArgs e)
{
GameController.Instance.LoadNewGame();
}
}
InGameMenu:
public partial class InGameMenu : UserControl
{
public InGameMenu()
{
InitializeComponent();
}
private void btnLoadSaved_Click(object sender, EventArgs e)
{
GameController.Instance.LoadSavedGame("test");
}
}
Notice how these two do nothing but call methods on the Controller. Easy.
public partial class MainScreen : UserControl
{
public MainScreen()
{
InitializeComponent();
GameController.Instance.Model.DateChanged += Model_DateChanged;
lblDate.Text = GameController.Instance.Model.DisplayDate;
}
void Model_DateChanged(object sender, EventArgs e)
{
lblDate.Text = GameController.Instance.Model.DisplayDate;
}
void Instance_CurrentGameChanged(object sender, EventArgs e)
{
throw new NotImplementedException();
}
private void btnEndTurn_Click(object sender, EventArgs e)
{
GameController.Instance.EndTurn();
}
}
This is a little more involved, but not very. The key is, it wires up the DateChanged event on the model. This way it can be notified when the date is incremented. I also implemented another game function (end turn) in a button here.
If you duplicate this and run it, you'll find that the game date is manipulated from lots of places, and the label is always updated properly. Best of all, your controller and model don't actually know anything at all about the View-- not even that it's based on WinForms. You could as easily use those two classes in a Windows Phone or Mono context as anything else.
Does this clarify some of the architecture principles I and others have been trying to explain?
In essence the problem is that when the application runs, it's going to try to instantiate the main form-window. But by using the Singleton pattern, you're essentially forbidding the application from doing that.
Take a look at the sample code here:
http://msdn.microsoft.com/en-us/library/system.windows.forms.application.aspx
You'll notice in particular this section:
[STAThread]
public static void Main()
{
// Start the application.
Application.Run(new Form1());
}
Notice how the program is trying to instantiate Form1. Your code says, nah, I don't really want that since you mark the constructor as private (same holds true for static forms as well). But that's counter to how windows forms is supposed to work. If you want a singleton form-window, just don't make any more. Simple as that.

Method call unexpected behaviour on UI

I am trying to learn how to call methods throughout a Wpf application.
In a basic experiment, I have two pages, PageData and MainPage.
PageData code:
namespace AppName
{
public sealed partial class PageData
{
public PageData()
{
this.InitializeComponent();
}
// works
private void Button_Click_1(object sender, RoutedEventArgs e)
{
mTest();
}
public bool mTest()
{
var newTbx = new TextBox{
Text = "Hello",
FontSize = 50
};
Grid.SetRow(newTbx, 3);
Grid.SetColumn(newTbx, 3);
gridMainPageData.Children.Add(newTbx);
return true;
}
}
}
MainPage code:
namespace AppName
{
public sealed class MainPage
{
public MainPage()
{
InitializeComponent();
}
private void pageRoot_Loaded(object sender, RoutedEventArgs e)
{
PageData passCall = new PageData();
mDisplayAlert(passCall.mTest().ToString());
}
}
}
It seems that the method mTest() completes because I get the "true" response when MainPage loads (I have a method mDisplayAlert that I use for showing messages on the MainPage UI), but the UI on PageData does not change. I know that mTest() works because the button click event on PageData does work.
Why does the UI not update when called from MainPage?
Because you create a new instance of PageData inside MainPage when what you really want to do is use the same instance to access the exact same controls. When you call the .test() method you create a totally new TextBox and assign data to a totally new Grid when you think you are writing on you first PageData instance.
You have many options from there. You can :
Pass a reference of the PageData instance to you other form when you create it.
Create an event between the two classes with a reference to the PageData instance.
Make your method and controls Static in PageData to make sure the whole program share the same instance. (Not recommanded at all)
If you want a little work around, you can always set you method to Static and create a Static copy of the control's instance. Then the compiler will ask for a reference of a Static control and you can assign the instance copy using Controls.Find(yourControl).(Not a good practice either).
Personally i'd use option number 1 but now you know you have the choice.

Categories

Resources