WPF-深入浅出WPF-Section7 依赖属性(例程)

vs2008用于快速创建依赖属性的 snippet 是propdp:键入propdp 后连续两次按 TAb键

vs2008用于快速创建附加属性的 snippet 是propa:键入propa 后连续两次按 TAb键

####XAML代码

<!--demo1 -依赖属性-->
    <Window x:Class="Wpf_7_Section.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="深入浅出WPF-第七章例程" Height="300" Width="493">
    <Grid>
        <TextBox x:Name="text1" Background="LawnGreen" Margin="5,36,5,0" Height="50" VerticalAlignment="Top" />
        <TextBox x:Name="text2" Background="LightBlue" Margin="5,99,5,0" Height="50" VerticalAlignment="Top" />
        <Button x:Name="btn" Content="OK" Click="btn_Click" Height="20" Margin="216,0,216,64" VerticalAlignment="Bottom" />
    </Grid>
</Window>

####C#后台代码

namespace Wpf_7_Section
{
    /// <summary>
    /// Window1.xaml 的交互逻辑
    /// </summary>
    public partial class Window1 : Window
    {
        Student st = new Student();//demo1 依赖属性 -
        public Window1()
        {
            InitializeComponent();
            /*-------------------------------------------------------------------------------------------
            * demo1 依赖属性 利用Student 依赖对象关联两个TextBox
            ---------------------------------------------------------------------------------------------*/
            st.SetBinding(Student.NameProperty, new Binding("Text") { Source = this.text1 });
            this.text2.SetBinding(TextBox.TextProperty, new Binding("Name") { Source = st });
        }

        private void btn_Click(object sender, RoutedEventArgs e)
        {
            /*--------------------------------------------------------------------------------------
            * demo1 依赖属性 利用Student 依赖对象关联两个TextBox
            -----------------------------------------------------------------------------------------*/
            //Student st = new Student();
            //st.Name = this.text1.Text;
            //this.text2.Text = st.Name;
        }
    }
}

####依赖属性定义

namespace Wpf_7_Section
{
    class Student:DependencyObject
    {
     
        //输入 propdp 按两下 Tab键 自动载入 标准的依赖属性定义
         
              //CLR属性包装器
        public String Name
        {
            get { return (String)GetValue(NameProperty); }
            set { SetValue(NameProperty, value); }
        }
        //依赖属性 第四个参数 不太清楚用法
        public static readonly DependencyProperty NameProperty =
            DependencyProperty.Register("Name", typeof(String), typeof(Student));
        //暂时借用FrameworkElement的SetBinding方法
        public BindingExpressionBase SetBinding(DependencyProperty dp, Binding binding)
        {
            return BindingOperations.SetBinding(this, dp, binding);
        }
    }
}

posted @ 2014-01-06 10:06  leanee  阅读(330)  评论(0)    收藏  举报