• 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"/>
  • 相关阅读:
    第一次 实习笔记
    docker 提示 Drive has not been shared 错误
    使用matplotlib画出log的图像
    python基础实现tcp文件传输
    django简单实现注册登录模块
    python使用消息队列RabbitMq(进阶)
    scrapy爬虫值Items
    redis常见配置redis.conf
    js实现往数组中添加非存在的对象,如果存在就改变键值。
    CSS之user-select——设置标签中的文字是否可被复制
  • 原文地址:https://www.cnblogs.com/Khan-Sadas/p/11077242.html
Copyright © 2020-2023  润新知