WPF学习笔记-控件之间绑定

实现一个按钮背景随着List的颜色选项变色。

 1 <Window x:Class="WPFdemo5.MainWindow"
 2         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
 3         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
 4         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
 5         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
 6         xmlns:local="clr-namespace:WPFdemo5"
 7         mc:Ignorable="d"
 8         Title="MainWindow" Height="350" Width="525">
 9     <Grid>
10         <ListBox x:Name="listBox" HorizontalAlignment="Left" Height="197" Margin="355,58,0,0" VerticalAlignment="Top" Width="127">
11             <ListBoxItem Height="20" Tag="Red" Content="Red"/>
12             <ListBoxItem Height="20" Tag="Blue" Content="Blue"/>
13             <ListBoxItem Height="20" Tag="Green" Content="Green"/>
14             
15         </ListBox>
16         <Button x:Name="button" Content="Button" HorizontalAlignment="Left" Margin="92,97,0,0"  Background="{Binding ElementName=listBox,Path=SelectedItem.Tag ,Mode=OneWay}" VerticalAlignment="Top" Width="75" Height="80"/>
17 
18     </Grid>
19 </Window>
View Code

效果图:

 Background="{Binding ElementName=listBox,Path=SelectedItem.Tag ,Mode=OneWay}"

Binding 中 ElementName=listBox  绑定控件的Name,Path=SelectedItem.Tag  绑定控件的什么属性值,Mode=OneWay 绑定控件的方式

A,B两控件: A属性值绑定B属性值

TwoWay:双向绑定,两者之间,改一个动两者,B一直变,则A一直变;A一直变则B也一直变

OneWay :单向绑定,B一直变,则A一直变

OneTime:单次绑定,B一直变,则A不一直变,只随着A初始值变一次

OneWayToSource:逆向绑定,A一直变,则B一直变

Default:默认,一般情况下用户可编辑控件属性(例如文本框和复选框的属性)默认为双向绑定,而多数其他属性默认为单向绑定。

后台代码绑定和解绑

 1   //声明和初始化绑定
 2             Binding b = new Binding();
 3             //绑定源,控件name
 4             b.Source = this.listBox;
 5             //绑定源的属性值
 6             b.Path = new PropertyPath("SelectedItem.Tag");
 7             //绑定方式
 8             b.Mode = BindingMode.OneWay;
 9             //要绑定控件的属性,绑定对象
10             this.button.SetBinding(Button.BackgroundProperty, b);
11 
12 
13             //删除绑定
14             BindingOperations.ClearAllBindings(this.button);
View Code

猜你喜欢

转载自www.cnblogs.com/anyihen/p/12926655.html