zoukankan      html  css  js  c++  java
  • RegisterAttached 两种绑定方式

    1. RegisterAttached 含义:使用指定的属性名称、属性类型和所有者类型注册附加属性
    2. 绑定方式:C#绑定、WPF绑定
    3. 例:需求DataViewModel为DataView的VM层,在DataViewModel中有ID属性,DataView需要根据ViewModel中的ID变化处理问题
     public class DataViewModel : INotifyPropertyChanged
        {
            public event PropertyChangedEventHandler PropertyChanged;
            public void OnPorpertyChanged(string name)
            {
                if (PropertyChanged != null)
                {
                    PropertyChanged.Invoke(this, new PropertyChangedEventArgs(name));
                }
            }
    
            public int ID
            {
                get { return id; }
                set
                {
                    id = value;
                    OnPorpertyChanged("ID");
                }
            }
            private int id;
        }
    /// <summary>
        /// DataView.xaml 的交互逻辑
        /// </summary>
        public partial class DataView : UserControl
        {
            public DataView()
            {
                InitializeComponent();
                this.DataContext = new DataViewModel();
            }
    
            public int ID
            {
                get { return (int)GetValue(IDProperty); }
                set { SetValue(IDProperty, value); }
            }
    
            public static readonly DependencyProperty IDProperty =
                DependencyProperty.RegisterAttached("ID", typeof(int), typeof(DataView), new PropertyMetadata(OnIDChanged));
    
            private static void OnIDChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
            {
                var control = d as MainWindow;
                if (control != null)
                {
                    control.Background = Convert.ToInt32(e.NewValue) > 0 ? Brushes.Red : Brushes.Green;
                }
            }
        }

      绑定方式1:

      在DataView.cs文件中使用Binding属性,如下:

    1             Binding binding = new Binding("ID");
    2             binding.Source = DataContext;
    3             binding.Mode = BindingMode.OneWay;
    4             this.SetBinding(MainWindow.IDProperty, binding);

       绑定方式2:

      在DataView.xaml文件中对控件的附加依赖属性进行绑定,如下:

    <TextBlock Text="{Binding ID}" Width="100" Height="50" Background="DarkGray"/>
  • 相关阅读:
    SQL Server 【应用】行列转换Pivot&Unpivot
    SQL Server 【优化】in & exists & not in & not exists
    SQL Server 【提高】 死锁
    SQL Server 【提高】 锁
    SQL Server 【提高】 游标
    .Net 【基础回顾】关键字
    .Net 【基础回顾】值类型与引用类型
    mysql中point类型数据的操作
    CGI环境配置(Ubuntu)
    CGI环境配置(CentOS)
  • 原文地址:https://www.cnblogs.com/Khan-Sadas/p/11077242.html
Copyright © 2011-2022 走看看