Reputation: 477
Can access an control (image)
from another class in C#
, XAML
?
For example: In class A (image) is collapsed/hidden, when check if image is collapsed/hidden in class B, i want to be visible/enabled, it's possible?
Thanks!
Upvotes: 0
Views: 118
Reputation: 565
You can use the PhoneApplicationService
to do it.
For example:
Suppose you navigated from class A
to class B
.
In class B
, before you navigate back to class A, set
PhoneApplicationService.Current.State["showImage"] = true;
In class A
, implement OnNavigatedTo
to handle it:
protected override void OnNavigatedTo(NavigationEventArgs e)
{
if (PhoneApplicationService.Current.State.ContainsKey("showImage"))
{
bool showImage = (bool)PhoneApplicationService.Current.State["showImage"];
if (showImage)
{
this.YourImage.Visibility = System.Windows.Visibility.Visible;
}
else
{
this.YourImage.Visibility = System.Windows.Visibility.Collapsed;
}
PhoneApplicationService.Current.State.Remove("showImage");
}
}
EDIT:
For multiple images, you can try the following approach:
In class B
, instead of passing a bool
to the PhoneApplicationService
, pass a Dictionary
of bools, each one representing the state of a image:
var showImage = new Dictionary<int, bool>();
showImage[1] = true;
showImage[2] = false;
showImage[3] = true;
PhoneApplicationService.Current.State["showImage"] = showImage;
In class A
, create a dictionary for your images:
private Dictionary<int, Image> _images = new Dictionary<int, Image>();
Then in its constructor, fill the dictionaries with your Images:
InitializeComponent();
_images[1] = YourImage1;
_images[2] = YourImage2;
_images[3] = YourImage3;
In class A
's OnNavigatedTo
, do:
protected override void OnNavigatedTo(NavigationEventArgs e)
{
if (PhoneApplicationService.Current.State.ContainsKey("showImage"))
{
var showImage = PhoneApplicationService.Current.State["showImage"] as Dictionary<int, bool>;
if (showImage != null)
{
foreach (var key in showImage.Keys)
{
if (_images.ContainsKey(key))
{
if (showImage[key])
{
_images[key].Visibility = System.Windows.Visibility.Visible;
}
else
{
_images[key].Visibility = System.Windows.Visibility.Collapsed;
}
}
}
}
}
}
If you prefer, you can change the key of the dictionaries for a more representative string.
Hope it helps! :)
Upvotes: 1