c# - Is it possible to change the Visibility property of a TextBox with the click of a button in another class(another wpf window)?
问题描述
I'm trying to change the Visibility property of a TextBox in one window by clicking the button in another window. It does not work with the current code i have. It is easy to do with a button and a TextBox that are in the same class but in separate classes it doesn't work. This is the code behind for the window that has the button i want to press to change the other window's textbox.
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
}
private void Button2_Click(object sender, RoutedEventArgs e)
{
MainWindow mainWindow = new MainWindow();
mainWindow.Box.Visibility = Visibility.Visible;
}
}
}
this is the code for the window whose textbox i want to change
<Grid Background="Blue">
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<TextBox Name="Box" Text="" Visibility="Hidden"/>
<Button Name="Buttons" Grid.Column="1" Content="Button" Click="Button_Click"/>
</Grid>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Window1 window1 = new Window1();
window1.Show();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
Box.Visibility = Visibility.Visible;
}
}
}
解决方案
是的!您可以为此使用 Mediator 类
public class Mediator
{
static readonly Mediator instance = new Mediator();
public static Mediator Instance
{
get
{
return instance;
}
}
private Mediator()
{
}
private static Dictionary<string, Action<object>> subscribers = new Dictionary<string, Action<object>>();
public void Register(string message, Action<object> action)
{
subscribers.Add(message, action);
}
public void Notify(string message, Object param)
{
foreach (var item in subscribers)
{
if (item.Key.Equals(message))
{
Action<object> method = (Action<object>)item.Value;
method.Invoke(param);
}
}
}
}
将此类添加到您的项目中,然后我主窗口的构造函数您创建调解器实例
Mediator _Mediator
public MainWindow()
{
InitializeComponent();
_Mediator= Mediator.Instance;
_Mediator.Register("ButtonVisibility",ChangeButtonVisibility);
}
private void ChangeButtonVibility(object obj)
{
this.button.Visibility=Visibility.Hidden;
}
在您的其他窗口构造函数中应该是这样的
Mediator _Mediator;
public MainWindow1(Mediator _mediator)
{
InitializeComponent();
_Mediator=_mediator;
}
//ON button click u notify like this
private void button_click(object sender, RoutedEventArgs e)
{
_Mediator.Notify("ButtonVisibility",null)
}
当您从主窗口初始化子窗口时
MainWindow1 window1= new MainWindow(_Mediator);
注意:在 MVVM 模式中使用了 Mediator 类,但它可以在这种情况下提供帮助。
推荐阅读
- python - 多处理过程在创建时直接启动
- unreal-engine4 - 查看对象虚幻时如何显示小部件?
- python - 根据索引位置对列值执行函数
- apache-spark - 类 org.apache.oozie.action.hadoop.SparkMain 未找到
- javascript - 让网络通知也在智能手机浏览器中工作?
- javascript - 函数启动其他函数时的变量可访问性 - javascript
- php - 为什么他们自动将“<”更改为<
- java - 如何将流中的所有元素减少到一个公共字段?
- android - 根据 Flavor 在 Android Studio 中显示布局
- oauth-2.0 - LinkedIn API 2 和 VanityName 来自 r_basicprofile