繁体   English   中英

在WPF中,从单独的类访问XAML文件中实例化的控件?

[英]In WPF, access a control that is instantiated in a XAML file from a separate Class?

WPF项目中有一个类,我们要访问放置在XAML文件中的控件。 我将代码放在下面和文件结构中,以帮助解决我的问题。

文件夹结构: Navigation Directors \\ FullKioskDirector.cs

MasterTemplates \\ SellAllKioskMaster.xaml

视图\\页面\\ 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
         */
         }

我该怎么做?

如果您以MVVM方法执行此操作,则最好不要执行代码背后的所有操作。

不过,无论您在创建FullKioskDirector任何地方,都只需将pageAttract传递给构造函数即可。

假设您在UserControl的构造函数中创建FullKioskDirector

public UserControl()
{
  var fullKioskDirector = new FullKioskDirector(pageAttract);
}

然后你可以像这样使用它

public FullKioskDirector(PageAttractScreen pageAttract)
{
   pageAttract.Visibility = Visibility.Collapsed;
}

我将使用“发布/订阅”模式。

示例:MessageBus / EventAggregator

在处理依赖项挑战时,这是我选择的工具。

本质上,您只是发布一条消息以使订阅者做出反应。 在这种情况下,您的订户将以控件的形式发布响应。

您可以利用Bizmonger.Patterns获取MessageBus。

https://msdn.microsoft.com/zh-CN/library/ff921122.aspx

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM