Reputation: 3924
We have a class in our WPF project that we want to access a control that is put into a XAML file. I have put my code below and file structure to help with my question.
Folder Structure: Navigation Directors\ FullKioskDirector.cs
MasterTemplates \ SellAllKioskMaster.xaml
Views \ Pages \ PageTemplates \ PageAttractScreen.xaml
We want 'FullKioskDirector.cs' to access the visibility of 'PageAttractScreen.xaml'. The 'SellAllKioskMaster.xaml' is referencing the 'PageAttractScreen.xaml' in its XAML.
Here is our code below.
SellAllKioskMaster.xaml
<UserControl
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:UserControls="clr-namespace:Kiosk.Views.Pages.UserControls" xmlns:PageTemplates="clr-namespace:Kiosk.Views.Pages.PageTemplates" x:Class="Kiosk.MasterTemplates.MyContainer"
mc:Ignorable="d"
d:DesignHeight="1049" d:DesignWidth="1912" Background="White">
<Grid>
<!--I need to access the visibility of these elements from the 'FullKioskDirector.cs'-->
<PageTemplates:PageAttractScreen x:Name="pageAttract" Margin="0,100"/>
<PageTemplates:PageWelcomeScreen x:Name="pageWelcome" Margin="0,100"/>
<PageTemplates:PageProductsScreen x:Name="pageProducts" Margin="0,100"/>
</Grid>
</UserControl>
FullKioskDirector.cs
using System;
using System.Windows;
using System.Windows.Controls;
using Kiosk.Common.Common.Contracts;
using Kiosk.Views.Pages.UserControls;
namespace Kiosk.Directors
{
public class FullKioskDirector : IPageNavigation
{
public FullKioskDirector()
{
/*
Want to control visibility of my controls that are placed and
x:Named in the SellAllKioskMaster.xaml
*/
}
How can I accomplish this?
Upvotes: 0
Views: 125
Reputation: 11570
I would use a Publish / Subscribe pattern.
Example: MessageBus / EventAggregator
This is my tool of choice when dealing with dependency challenges.
Essentially, you just post a message for subscribers to react to. In this case your subscriber will then post a response in the form of a control.
You can leverage Bizmonger.Patterns to get the MessageBus.
https://msdn.microsoft.com/en-us/library/ff921122.aspx
Upvotes: 0
Reputation: 10865
It's better if you do it in an MVVM
approach, rather than doing everything from code behind.
Nevertheless, wherever you are creating FullKioskDirector
, just pass in pageAttract
to the constructor.
Assuming you create the FullKioskDirector
at UserControl
's constructor
public UserControl()
{
var fullKioskDirector = new FullKioskDirector(pageAttract);
}
Then you can use it like this
public FullKioskDirector(PageAttractScreen pageAttract)
{
pageAttract.Visibility = Visibility.Collapsed;
}
Upvotes: 2