当前位置:首页 > Windows程序 > 正文

简单绑定学习

2021-05-25 Windows程序

1. 绑定到元素对象.(实际项目中用处不大)

界面上两个关联的控件之间绑定,比如一个TextBlock 的FontSize和一个Slider 的Value绑定:

<Slider Name="sliderFontText" Minimum="1" Maximum="100" Value="10"/> <TextBox Name="txtValue" Width="200" Text="{Binding ElementName=sliderFontText, Path=Value,UpdateSourceTrigger=PropertyChanged,Mode=TwoWay}"/>

Text的内容就是new了一个Binding对象,设置ElementName,Path等是绑定的属性值.

XAML对应的C#代码:

Binding binding = new Binding(); binding.ElementName = "sliderFontText"; binding.Path = new PropertyPath("Value"); binding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged; binding.Mode = BindingMode.TwoWay; txtValue.SetBinding(TextBox.TextProperty, binding);

删除绑定:

BindingOperations.ClearBinding(txtValue, TextBox.TextProperty);

绑定后属性的操作,如删除绑定,获取控件绑定对象,都可以使用System.Windows.Data.BindingOperations的静态方法.

   BandingModel枚举值介绍:

名称

 

说明

 

OneWay

 

源属性 -> 目标属性(源变化引发目标变化)

 

TwoWay

 

源属性 <-> 目标属性(源变化引发目标变化且目标变化也引发源变化)

 
OneTime  

首次执行 源属性 -> 目标属性,后面所有变化忽略(除非显示调用BindingExpress.UpdateTarget()或者重新绑定完全不同的对象

 

OneWayToSource

 

和OneTime绑定方式相反

 
Default  

依赖绑定目标属性

 

UpdateSourceTrigger枚举值介绍:

名称

 

说明

 

PropertyChanged

 

目标属性变化 -> 立即更新源

 

LostFocus

 

目标属性变化 + 目标失去焦点 -> 更新源

 

Explicit

 

调用BindingExpression.UpdateSource() -> 更新源

 

Default

 

大部分为PropertyChanged,Textbox.Text是LostFocus

 

2. 绑定非界面元素

1.    绑定静态类的静态属性(系统预定义和自定义方法一致,这里演示一个自定义):

XAML(c是 命名空间WPFDemo的别名):

<Button Content="{Binding Source={x:Static c:MyRes.Name}}"/>

C#: 

namespace WPFDemo
{
    public static class MyStaticRes
    {
        public static string Name { get { return "返回的Name"; } }
    }

}

2.绑定一般类的一般属性

XAML:首先需要新建一个资源对象,,

创建资源对象:

<Window.Resources> <c:MyRes x:Key="customRes" Name="自定义资源文本"></c:MyRes> </Window.Resources>

XAML绑定:

<Button Content="{Binding Source={StaticResource customRes},Path=Name}"/>

C#:

namespace WPFDemo { public class MyRes { public string Name { get; set; } } }

3. 相对绑定

XAML(这里将StackPanel的Name绑定到Button的Content属性中):

<StackPanel x:Name="LayoutRoot"> <Button Content="{Binding Path=Name, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type StackPanel}}}"/> </StackPanel>

RelativeSource 的Model枚举值值:

名称   说明  
Self   绑定自己的另外一个属性  
FindAncestor   绑定到父元素,需要设置父元素类型AncestorType和父元素层次AncestorLevel(默认为1)  
PreviousData   绑定到数据绑定列表的前一项  
TemplateParent   绑定到应用模板的元素  

     4.DataContext绑定

温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/70840.html