Data Binding数据驱动

Data Binding数据驱动

一、简介

在XAML文件中我们创建了一个TextBlock 和一个Slider。2个控件。我们把TextBlock的Text属性(用于显示文本的属性)设置为{Binding Intelligence}。把Slider的Value属性(滑块的当前值)设置为{Binding Intelligence}。

二、代码案例

XMAL:

  <Grid>
        <StackPanel>
            <TextBlock Text="{Binding Intelligence}"/>
            <!--通过数据驱动修改绑定值得属性-->
            <TextBox Text="{Binding Intelligence,Mode=TwoWay}"/>           
            <Slider Minimum="1" Maximum="100" Value="{Binding Intelligence}"/>
            <StackPanel Orientation="Horizontal">
                <TextBlock Text="名称:"/>
                <TextBlock Text="{Binding Name}" MinWidth="120"/>
                <TextBlock Text="请输入需要修改的名称:"/>
                <TextBox MinWidth="120" x:Name="tb_inputName"/>
            </StackPanel>
            <!--通过事件驱动修改绑定值得属性-->
            <Button Content="事件驱动修改绑定值。" Click="AlertText_Click"/>
        </StackPanel>
    </Grid>

后台逻辑:

  public partial class MainWindow : Window
    {
        Person duwenlong;
        public MainWindow()
        {

            InitializeComponent();
            duwenlong = new Person();
            Binding binding = new Binding();
            binding.Source = duwenlong;
            binding.Mode = BindingMode.TwoWay;
            binding.Path = new PropertyPath("Name");
            BindingOperations.SetBinding(tb_inputName, TextBox.TextProperty, binding);
            this.DataContext = duwenlong;
        }

        private void AlertText_Click(object sender, RoutedEventArgs e)
        {
            duwenlong.Name = "点击按钮后>>>>";
        }
    }
    public class Person : INotifyPropertyChanged
    {
        private double _intelligence;
        public double Intelligence
        {
            get { return _intelligence; }
            set
            {
                _intelligence = value;
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Intelligence"));

            }
        }
        private string _name;
        public string Name
        {
            get { return _name; }
            set
            {
                _name = value;
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Name"));
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;
    }

三、运行效果

Data Binding数据驱动

 Data Binding数据驱动

 Data Binding数据驱动

Data Binding数据驱动

上一篇:配置服务器


下一篇:GridSplitter 可拖动