WPF入门笔记 三 数据绑定
作者:互联网
1.元素绑定
<Window x:Class="demo.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:demo"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800" Loaded="Window_Loaded" MouseLeftButtonDown="Window_MouseLeftButtonDown">
<Grid>
<StackPanel>
<Slider x:Name="sd" Width="200"/>
<TextBox Text="{Binding ElementName=sd, Path=Value}"/>
</StackPanel>
</Grid>
</Window>
2.资源绑定
<Window x:Class="demo.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:demo"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800" Loaded="Window_Loaded" MouseLeftButtonDown="Window_MouseLeftButtonDown">
<Window.Resources>
<TextBox x:Key="txt" Text="hello"/>
</Window.Resources>
<Grid>
<StackPanel>
<TextBox Text="{Binding Source={StaticResource txt}, Path=Text}"/>
</StackPanel>
</Grid>
</Window>
3.绑定属性(第一种)
1.定义一个显示控件
<Grid>
<StackPanel>
<TextBox x:Name="txt" Text="{Binding MyVar, FallbackValue='Not Found'}"/>
</StackPanel>
</Grid>
2.先绑定数据上下文
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
txt.DataContext = new DataSource();
}
}
3.定义一个数据类
public class DataSource:INotifyPropertyChanged
{
public DataSource()
{
Task.Run(async () =>
{
await Task.Delay(3000);
MyVar = "3333";
});
}
private string _myVar = "2222";
public string MyVar
{
get { return _myVar; }
set { _myVar = value;
OnPropertychanged("MyVar");
}
}
public event PropertyChangedEventHandler PropertyChanged;
//通知UI更新
protected void OnPropertychanged(string properName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(properName));
}
}
}
4.绑定属性(第二种)
使用MVVM框架
1.安装 MVVMLight框架
2.编写绑定代码
//1.引用框架
using GalaSoft.MvvmLight;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace demo
{
//2.继承 ViewModelBase
public class DataSource:ViewModelBase
{
public DataSource()
{
Task.Run(async () =>
{
await Task.Delay(3000);
MyVar = "3333";
MyVar1 = "Hello Hello";
});
}
private string _myVar = "2222";
public string MyVar
{
get { return _myVar; }
set
{ _myVar = value;
//3.调用通知
RaisePropertyChanged();
}
}
private string myVar1="Hello";
public string MyVar1
{
get { return myVar1; }
set
{ myVar1 = value;
RaisePropertyChanged();
}
}
}
}
标签:入门,绑定,System,myVar,using,WPF,public,string 来源: https://blog.csdn.net/jinlin_0/article/details/110421140