(18)WPF 元素绑定
原创
©著作权归作者所有:来自51CTO博客作者富坚老贼的原创作品,请联系作者获取转载授权,否则将追究法律责任
绑定具有四个组成部分:
- 绑定目标对象。
- 目标属性。
- 绑定源。
- 绑定源中要使用的值的路径
被绑定目标属性必须是依赖项属性
一、绑定到元素
1.元素绑定
<StackPanel>
<Slider Name="slider" Width="300" Value="10" Minimum="0" Maximum="30" TickFrequency="1" IsSnapToTickEnabled ="True" TickPlacement="TopLeft"></Slider>
<Label Name="lable" FontSize="{Binding ElementName=slider,Path=Value}">hello</Label>
</StackPanel>
元素绑定 使用{Binding ElementName= ,Path= }
这种方式比valueChanged事件要简单
2.绑定模式
数据绑定的一个特性是目标会被自动更新,而不考虑元的修改方式
<Button Name="btn" Click="btn_Click" Width="80" Height="30"/>
private void btn_Click(object sender, RoutedEventArgs e)
{
slider.Value = 28;
}
*注意:如果在绑定了元素的情况下对lable进行字体设置
private void btn_Click(object sender, RoutedEventArgs e)
{
lable.FontSize = 28;
}
这将会使元素绑定失效,怎么滑动lable都不会再发生变化
解决办法,可以通过双向绑定的方式进行绑定
<Label Name="lable" FontSize="{Binding ElementName=slider,Path=Value,Mode=TwoWay}">hello</Label>
Mode的值
OneWay 当源属性变化时更新目标属性
TwoWay 双向更新
OneWayToSource 在目标属性更改时,更新源属性
OneTime 仅当应用程序启动时或 DataContext 进行更改时更新目标属性???
Default 默认以上方式中的一种
3.使用代码绑定
Binding binding = new Binding();
binding.Source = slider;
binding.Path = new PropertyPath("Value");
binding.Mode = BindingMode.TwoWay;
lable.SetBinding(Label.FontSizeProperty, binding);
取消绑定
private void btn_Click(object sender, RoutedEventArgs e)
{
BindingOperations.ClearAllBindings(lable);
}
一般使用xaml的方式绑定,但当创建动态绑定或删除绑定时需要用代码的方式。
4.代码检索绑定
private void btn_Click(object sender, RoutedEventArgs e)
{
Binding binding = BindingOperations.GetBinding(lable, Label.FontSizeProperty);
MessageBox.Show(binding.Source.ToString() + " 2:" + binding.Path.ToString() + " 3: "+binding.Mode.ToString());
}
5.多绑定
6.更新绑定
反向从目标到源的改变不一定会立即发生,
Binding binding = new Binding();
binding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
或者
<Label Name="lable" FontSize="{Binding ElementName=slider,Path=Value,Mode=OneTime,UpdateSourceTrigger=PropertyChanged}">hello</Label>
- PropertyChanged 每当绑定目标属性发生更改时,都会更新绑定源
- LostFocus 每当绑定目标元素失去焦点时,都会更新绑定源
- Explicit 仅在调用 UpdateSource() 方法时更新绑定源
- Default 绑定目标属性的默认 UpdateSourceTrigger 值。 大多数依赖属性的默认值为 PropertyChanged,而 Text 属性的默认值为 LostFocus
7.延迟绑定
避免频繁操作,延迟500毫秒
<Label Name="lable" FontSize="{Binding ElementName=slider,Path=Value,Mode=OneTime,Delay=500}">hello</Label>
二、绑定到非元素对象
1.Source
绑定到提供数据的对象
2.RelativeSource
根据相对于目标对象的关系指向源对象
3. DataContext
将大量元素绑定到同一个对象