WPF之绑定
绑定的几种方式
1 元素绑定
<Grid> <StackPanel > <TextBox x:Name="t1" HorizontalAlignment="Left" Margin="35,26,0,0" TextWrapping="Wrap" Height="25" Width="266"/> <!--元素绑定:绑定Name值为t1的元素,Path=Text表示将这个元素值的Text值赋给当前元素的Text属性--> <TextBox Text="{Binding Text, ElementName=t1}" HorizontalAlignment="Left" Margin="35,71,0,0" VerticalAlignment="Top" Height="26" Width="266"/> </StackPanel> </Grid>
3 绑定后台业务代码
比如后台有如下类:
public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); //注意要在这里将数据添加到上下文中 this.DataContext = new TestModel(); } } public class TestModel { public TestModel() { Name = "Hello"; } private string name; public string Name { get => name; set => name = value; } } }
xaml中绑定:
<Window x:Class="MyWpf.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" mc:Ignorable="d" Title="MainWindow" Height="296.042" Width="347.333" > <Grid> <StackPanel > <TextBlock Text="{Binding Name,FallbackValue='error'}" HorizontalAlignment="Left" Margin="35,71,0,0"
VerticalAlignment="Top" Height="26" Width="266"/> </StackPanel> </Grid> </Window>
我们还可以换一种方式写,用强类型视图的方式来写,直接在xaml文件中指定当前上下文用什么模型:
<Window x:Class="MyWpf.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" mc:Ignorable="d" xmlns:local="clr-namespace:MyWpf" Title="MainWindow" Height="296.042" Width="347.333" > <Window.DataContext> <!--之所在这里能直接这样写,是因为前面属性中引入了这个类的命名空间, xmlns:local="clr-namespace:MyWpf" --> <local:TestModel></local:TestModel> </Window.DataContext> <Grid> <StackPanel > <TextBlock Text="{Binding Name,FallbackValue='error'}" HorizontalAlignment="Left" Margin="35,71,0,0"
VerticalAlignment="Top" Height="26" Width="266"/> </StackPanel> </Grid> </Window>
这样写的话,在Binding中就会有提示有哪些属性是可以被绑定的。
1