WPF数据绑定要经过三步骤
1.定义数据源
2.定义上下文
3.数据绑定
先看下静态绑定
using System;
using System.Collections.Generic;
using System.Text;
namespace WpfApp1
{
public class ColorData
{
private string colorName = "red";
public string ColorName { get => colorName; set => colorName = value; }
public String Content { get; set; }
}
}
<Window x:Class="WpfApp1.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:WpfApp1"
mc:Ignorable="d"
xmlns:s="clr-namespace:WpfApp1"
Title="MainWindow" Height="450" Width="800" Loaded="Window_Loaded">
<Grid>
<Grid.Resources>
<s:ColorData x:Key="colorSource"></s:ColorData>
</Grid.Resources>
<Grid.DataContext>
<Binding Source="{StaticResource colorSource}"></Binding>
</Grid.DataContext>
<Button x:Name="btn" Content="{Binding Path=Content}" Background="{Binding Path=ColorName}" Width="150" Height="50"></Button>
</Grid>
</Window>
静态绑定按钮的背景色,
使用Grid.Resources 先定义资源
使用 Grid.DataContext定义上下文访问对象
Background="{Binding Path=ColorName}" 绑定资源属性
动态绑定
private void Window_Loaded(object sender, RoutedEventArgs e)
{
btn.DataContext = new ColorData() { Content="按钮"};
}
绑定按钮显示内容 Content="{Binding Path=Content}"
总之,数据源可以是动态的和静态绑定两种,使用Binding绑定数据,