WPF基础入门
Class4:WPF绑定
一、简单绑定数据
1、cs文件中设置需要绑定的数据:
public partial class Class_4 : Window{public Class_4(){InitializeComponent();List<Color> test = new List<Color>();test.Add(new Color() { Code = "Yellow", Name = "Red" });test.Add(new Color() { Code = "#00FF00", Name = "Green" });test.Add(new Color() { Code = "#0000FF", Name = "Blue" });//数据绑定到gridgrid.ItemsSource = test;}}public class Color{public string Code { get; set;}public string Name { get; set; }}
2、编写xaml绑定
<Grid><!--AutoGenerateColumns和CanUserAddRows去掉多余的行列--><DataGrid x:Name="grid" AutoGenerateColumns="False" CanUserAddRows="False"><DataGrid.Columns><DataGridTextColumn Binding="{Binding Code}" Header="Code"></DataGridTextColumn><DataGridTextColumn Binding="{Binding Name}" Header="Name"></DataGridTextColumn><DataGridTextColumn Header="操作"></DataGridTextColumn><DataGridTemplateColumn Header="操作"><DataGridTemplateColumn.CellTemplate><DataTemplate><StackPanel Orientation="Horizontal"><Border Width="10" Height="10" Background="{Binding Code}"></Border><TextBlock Margin="10,0" Text="{Binding Name}"></TextBlock></StackPanel></DataTemplate></DataGridTemplateColumn.CellTemplate></DataGridTemplateColumn></DataGrid.Columns></DataGrid></Grid>
3、效果显示:
二、控件绑定
1、Binding ElementName
:绑定的元素
2、Path=绑定的属性
3、Mode
:绑定的模式,default双向榜单TwoWay
Mode绑定模式,onetime只改变一次
default默认双向
OneWay只能受到影响
OneWayToSource只能影响源ElementName,不收到源的影响
<Grid><StackPanel><!--WPF的控件数据绑定--><!--滑块--><Slider x:Name="slide" Margin="5" ValueChanged="Slider_ValueChanged"></Slider><TextBox x:Name="txt1" Margin="5" Height="30"Text="{Binding ElementName=slide, Path=Value,Mode=OneWayToSource}"></TextBox><TextBox x:Name="txt2" Margin="5" Height="30" Text="{Binding ElementName=slide, Path=Value, Mode=OneWay}"></TextBox><TextBoxx:Name="txt3" Margin="5" Height="30"Text="{Binding ElementName=slide, Path=Value, Mode=TwoWay}"></TextBox></StackPanel>
</Grid>