wpf用户控件和表单之间如何调用

分类:网络文章 时间:2024-01-15 08:12 浏览:0 评论:0
0

在WPF中,用户控件和表单可以通过以下方式调用:

  1. 通过事件:用户控件可以定义事件,表单可以订阅事件事件。事件,当用户控件中发生操作时,会在表单中触发并处理相应的事件。用户控件中定义的事件:

    public partial class MyUserControl : 用户控件{ public 事件 EventHandler MyEvent; public MyUserControl() { InitializeComponent() ; } 私有 void Button_Click(对象发​​送者,RoatedEventArgs e) { MyEvent?.Invoke(this, EventArgs .Empty); }}

    以以下形式订阅事件:

    public < span class="hljs-keyword">部分  class 主窗口 : 窗口 { 公共 主窗口() { 初始化组件( ); myUserControl.MyEvent += MyEventHandler; } 私有 void MyEventHandler(对象 发送者,EventArgs e)  { //处理用户控件触发的事件 }}
  2. 通过公共方法:用户控件可以定义公共方法,窗体可以直接调用该方法进行操作。用户控件中定义的公共方法:

    public partial class MyUserControl : UserControl{ < span class="hljs-function">public MyUserControl() { InitializeComponent(); } 公共 void DoSomething() { //执行一些操作 }}

    调用形式:

    公共 部分 class 主窗口 : 窗口{ public 主窗口() { InitializeComponent(); } 私有 void Button_Click(对象发​​送者,RotedEventArgs e) { myUserControl.DoSomething( ); }}
  3. 通过数据绑定:用户控件可以定义依赖属性,表单可以将数据绑定到属性上。当属性发生变化时,表单可以获得最新的值进行处理。在用户控件中定义依赖属性:

    public partial  MyUserControl : 用户控件{ 公共 静态 < span class="hljs-keyword">只读 DependencyProperty MyPropertyProperty = DependencyProperty.Register ("MyProperty", typeof (字符串), typeof(MyUserControl)); 公共 字符串 MyProperty { 获取 { return (字符串)GetValue(MyPropertyProperty); } 设置 { SetValue(MyPropertyProperty, ); } } public MyUserControl() { InitializeComponent (); }}

    表单中的数据绑定:

       

    设置数据源并处理表单中的数据变化:

     公共 部分  主窗口 : 窗口, INotifyPropertyChanged{ 私有 字符串 myPropertyInMainWindow; 公共 字符串 MyPropertyInMainWindow { 获取 { 返回 myPropertyInMainWindow; } 设置 { myPropertyInMainWindow = ;氧nPropertyChanged(nameof(MyPropertyInMainWindow)); // 处理属性更改 } }  public 主窗口() { InitializeComponent(); DataContext =这个; } 公共 事件 PropertyChangedEventHandler PropertyChanged; 受保护 无效  OnPropertyChanged(字符串 propertyName) { PropertyChanged?.Invoke(这个 PropertyChangedEventArgs(propertyName)); }}

以上是用户控件与窗体之间调用的几种常用方法。你可以n 根据具体需要选择合适的调用方式。

1. 本站所有资源来源于用户上传或网络,仅作为参考研究使用,如有侵权请邮件联系站长!
2. 本站积分货币获取途径以及用途的解读,想在本站混的好,请务必认真阅读!
3. 本站强烈打击盗版/破解等有损他人权益和违法作为,请各位会员支持正版!
4. 网络文章 > wpf用户控件和表单之间如何调用

用户评论