我们的WPF项目中有一个类,我们想要访问放入XAML文件的控件。我已将下面的代码和文件结构放在我的问题上。
文件夹结构: 导航导演\ FullKioskDirector.cs
MasterTemplates \ SellAllKioskMaster.xaml
Views \ Pages \ PageTemplates \ PageAttractScreen.xaml
我们希望'FullKioskDirector.cs'能够访问'PageAttractScreen.xaml'的可见性。 'SellAllKioskMaster.xaml'在其XAML中引用了'PageAttractScreen.xaml'。
以下是我们的代码。
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
*/
}
我该如何做到这一点?
答案 0 :(得分:2)
如果你采用MVVM
方法,而不是从代码背后做任何事情,那就更好了。
然而,无论您在何处创建FullKioskDirector
,只需将pageAttract
传递给构造函数。
假设您在FullKioskDirector
的构造函数中创建了UserControl
public UserControl()
{
var fullKioskDirector = new FullKioskDirector(pageAttract);
}
然后你可以像这样使用它
public FullKioskDirector(PageAttractScreen pageAttract)
{
pageAttract.Visibility = Visibility.Collapsed;
}
答案 1 :(得分:0)
我会使用发布/订阅模式。
示例:MessageBus / EventAggregator
在处理依赖性挑战时,这是我的首选工具。
基本上,您只是发布消息给订阅者做出反应。 在这种情况下,您的订户将以控件的形式发布响应。
您可以利用Bizmonger.Patterns获取MessageBus。