WPF 自定义控件的依赖属性的绑定方法

首先一些人觉得WPF中前台的代码应该在前台创建,尽量不要在后台用代码创建。另外如果前台重复代码过多,编写起来非常繁琐而且修改更是头痛。因此使用用户控件的方法把经常使用的前台模块制作成控件,当然用法和普通控件基本相同。

注意的地方已经用红色标记,代码如下:

 

控件后台代码:

public partial class UC_ReagentWellTextBlock : UserControl
    {
        public UC_ReagentWellTextBlock()
        {
            //界面初始化
            InitializeComponent();

            //我这里需要绑定两个TextBlock,因此将这两个TextBlock进行绑定,绑定的是用于中转的变量,后续看的到.
            Binding bindInformation = new Binding("InformationText") { Source = this };
            this.TextBlockInformatioin.SetBinding(TextBlock.TextProperty, bindInformation);

            Binding bindPosition = new Binding("PositionText") { Source = this };
            this.TextBlockPosition.SetBinding(TextBlock.TextProperty, bindPosition);
        }

        //声明依赖属性.
        public static readonly DependencyProperty PositionTextProperty = DependencyProperty.Register("PositionText", typeof(string), typeof(UC_ReagentWellTextBlock));
        public static readonly DependencyProperty InformationTextProperty = DependencyProperty.Register("InformationText", typeof(string), typeof(UC_ReagentWellTextBlock));

        //声明中转的变量
        public string PositionText
        {
            get { return (string)GetValue(PositionTextProperty); }
            set { SetValue(PositionTextProperty, value); }
        }

        public string InformationText
        {
            get { return (string)GetValue(InformationTextProperty); }
            set { SetValue(InformationTextProperty, value); }
        }
    }

控件前台代码:

  
        
            
        

窗体调用控件后台:

           Binding bind2 = new Binding(bindStr);
           //数据绑定,等号后面的东西可以不用看,替换成其他的对象即可.
           well3_1.DataContext = IC_LABRARY.Instrument.Instrument.InstrumentRackSample.InstrumentWellSampleArray[2].InstrumentContainerTube.InformationManagementPatient;
           //绑定数据源,这里就是一开始想要实现的和基本控件一样的功能.
           well3_1.SetBinding(UC.UC_ReagentWellTextBlock.PositionTextProperty, bind2);
           well3_1.SetBinding(UC.UC_ReagentWellTextBlock.InformationTextProperty, bind2);


 

窗体调用控件前台:


    
        
        
        
            
    
    
        
            
            
            
            
            
            
            
            
            
            
            
        
        
            
            
            
            
            
        
   
   



温馨提示:CSDN的Blog第一天不允许发带链接的文章,否则将封号哦!

你可能感兴趣的:(WPF前端)