WPF数据驱动Data Binding
農碼一生 人气:3一、简介
在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 p; public MainWindow() { InitializeComponent(); p = new Person(); Binding binding = new Binding(); binding.Source = p; binding.Mode = BindingMode.TwoWay; binding.Path = new PropertyPath("Name"); BindingOperations.SetBinding(tb_inputName, TextBox.TextProperty, binding); this.DataContext = p; } private void AlertText_Click(object sender, RoutedEventArgs e) { p.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; }
三、运行效果
到此这篇关于WPF数据驱动修改绑定的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持。
加载全部内容