• WPF元素绑定


    简单的说,数据绑定是一种关系,该关系告诉WPF从源对象提取一些信息,并用这些信息设置目标对象的属性。目标属性始终是依赖属性,通常位于WPF元素中——毕竟,WPF数据绑定的最终目标是在用户界面中显示一些信息。然而,源对象可以是任何内容,从另一个WPF元素乃至ADO.NET数据对象(如DataTable、DataRow)或您自行创建的纯数据对象。

    将元素绑定到一起

    数据绑定最简单的情形是,源对象是WPF元素而且源属性是依赖项属性,依赖性属性具有内置的更改通知支持。因此,当在源对象中改变依赖项属性的值时,会立即更新目标对象中的绑定属性,这正是我们所需要的的行为——而且不必为此构建任何额外的基础结构。

    1. "sliderFontSize" Minimum="1" Maximum="40" Value="10" TickFrequency="1" />
    2. "textBlockFontSize" FontSize="{Binding ElementName=sliderFontSize, Path=Value, Mode=TwoWay}" Text="Simple Text"/>
    3. "textBlockFontSize2" Text="Simple Text"/>
    textBlockFontSize2.SetBinding(TextBlock.FontSizeProperty, new Binding("Value") { ElementName = "sliderFontSize", Mode=BindingMode.TwoWay });

    这里将两个TextBlock的FontSize属性绑定到Slider的Value属性上,其中一个通过绑定表达式设置,另一个则是通过代码设置,现在在滑动Slider的滑块时,两个TextBlock 的字体大小会随之发生变化。

    数据绑定表达式使用XAML标记扩展,也会创建一个Binding 类的实例,所以绑定表达式以 Binding 开头。

    使用代码创建绑定时,先创建一个绑定对象,构造函数参数指定Path字段,然后设置Binding相关的属性值,通过绑定目标的SetBinding函数,将绑定目标的属性与Binding对象关联即可。

    因为基于标记的绑定更清晰并且需要完成的工作更少,所以更常用。但在一些特殊情况下,会希望使用代码创建绑定:

    创建动态绑定  如果希望根据其他运行时信息修改绑定,或者根据环境创建不同的绑定,这时使用代码创建绑定通常更合理(此外,也可以在窗口的Resources集合中定义可能希望使用的每个绑定,并只添加使用合适的绑定对象调用SetBinding() 方法的代码)。

    删除绑定  如果希望删除绑定,从而可以通过普通方式设置属性,需要借助ClearBinding() 或 ClearAllBinding() 方法。仅为属性应用新值是不够的——如果正在使用双向绑定,设置的值会传播到链接的对象,并且两个属性保持同步。

    绑定错误

    WPF不会引发异常来通知与数据绑定相关的问题。如果指定的元素或属性不存在,那么不会收到任何指示,只是不能在目标属性中显示数据。WPF会输出绑定失败细节的跟踪信息。当调试应用程序时,该信息显示在Visual Studio 的输出窗口中。

    绑定模式

    绑定模式通过Binding.Mode 属性设置,WOF允许使用5个枚举值中的任何一个。

    OneWay:当源属性变化时更新目标属性

    TwoWay:当源属性变化时更新目标属性,并且当目标属性变化时更新源属性

    OneTime:最初根据源属性值设置目标属性,然后,其后的所有变化都会被忽略。通常,如果知道源属性不会变化,可使用这种模式降低开销

    OneWayToSource:与OneWay类似,但方向相反,当目标属性变化时更新源属性

    Default:此类绑定依赖于目标属性。既可以是双向的(对于用户可以设置的属性,如TextBox.Text),也可以是单向的(对于所有其它属性)。除非明确指定了一种模式,否则所有绑定都是用该方式。

    使用代码检索绑定

    可使用代码检索绑定并检查其属性,而不必考虑绑定最初是使用代码还是标记创建的。可采用两种方式来获取绑定信息:

    1、使用静态方法 BindingOperations.GetBinding() 来检索相应的Binding 对象。

    2、使用静态方法 BindingOperations.GetBindingExpression() 方法获得更实用的 BindingExpression对象。

    1. Binding binding = BindingOperations.GetBinding(textBlockFontSize, TextBox.FontSizeProperty);
    2. MessageBox.Show("Bound " + binding.Path.Path + " to source element " + binding.ElementName);
    3. //BindingExpression expression = BindingOperations.GetBindingExpression(textBlockFontSize, TextBlock.FontSizeProperty);
    4. BindingExpression expression = textBlockFontSize.GetBindingExpression(TextBlock.FontSizeProperty);
    5. MessageBox.Show("Bound " + expression.ResolvedSourcePropertyName + " with data " + ((Slider)expression.ResolvedSource).Value);

    多绑定

    可以为一个控件设置多个绑定,比如为TextBlock的FontSize、Text分别创建各自的绑定。

    甚至可以为同一个控件的同一个属性绑定至多个源。乍一看,这好像不可能实现,毕竟,当创建绑定时,只能指定一个目标属性,然而,可使用多种方法突破这一限制。最简单的方法是更改数据绑定模式,可以将Mode属性设置为TwoWay,这样可以在源上设置绑定到目标的绑定表达式。

    1. "sliderFontSize" Minimum="1" Maximum="40" Value="10" TickFrequency="1" />
    2. "textBlockFontSize" FontSize="{Binding ElementName=sliderFontSize, Path=Value, Mode=TwoWay}" Text="Simple Text"/>
    3. "textBlockFontSize2" Text="Simple Text"/>
    4. "txtContent" Text="{Binding ElementName=textBlockFontSize, Path=FontSize, Mode=TwoWay}"/>
    5. "txtContent2" Text="{Binding ElementName=sliderFontSize, Path=Value, Mode=TwoWay}"/>
    6. "{Binding ElementName=sliderFontSize, Path=Value, Mode=TwoWay}" Text="{Binding ElementName=txtContent, Path=Text}"/>

    双向绑定具有极大的灵活性,可使用它们从源向目标以及从目标向源应用改变。还可以组合应用它们来创建非常复杂的不需要编写代码的窗口。

    绑定更新

    当使用OneWay 或TwoWay 绑定模式时,改变后的值会立即从源传播到目标。然而,反向的变化传递——从目标到源——未必会立即发生。它们的行为由 Binding.UpdateSourceTrigger 属性控制:

    PropertyChanged: 当目标属性发生变化时立即更新源

    LostFocus:当目标属性发生变化并且目标丢失焦点时更新

    Explicit:除非调用BindingExpress.UpdateSource()方法,否则无法更新源

    Default:根据目标属性的元数据确定更新行为。大多数属性的默认行为是PropertyChanged,但TextBox.Text 属性的默认行为是LostFocus

    通过BindingExpress.UpdateSource()方法更新源的方式如下:

    1. BindingExpression expression = txtContent2.GetBindingExpression(TextBox.TextProperty);
    2. expression.UpdateSource();

    绑定延迟

    在极少数情况下,需要防止数据绑定触发操作和修改源对象,至少在某一时段是这样的。可使用Binding.Delay 属性,等待数毫秒,之后再提交更改。

    绑定到非元素对象

    当绑定到非元素对象时,需要放弃Binding.ElementName 属性,并使用一下属性中的一个:

    Source:该属性是指向源对象的引用——换句话说,是提供数据的对象

    RelativeSource:这是引用,使用RelativeSource 对象指向源对象。有了这个附加层,可在当前元素的基础上构建引用。这似乎无谓的增加了复杂程度,但实际上,RelativeSource 属性是一种特殊工具,当编写控件模板以及数据模板时是很方便的

    DataContext:如果没有使用Source或RelativeSource 属性指定源,WPF就从当前元素开始在元素数中向上查找,检查每个元素的DataContext 属性,并使用第一个非空的DataContext 属性。当我们要将同一个对象的多个属性绑定到不同的元素是,DataContext属性时非常有用的,因为可在更高陈词的容器对象上(而不是直接在目标元素上)设置DataContext 属性。

    Source属性

    Source属性非常简单,唯一的问题是为了进行绑定,需要具有数据对象。可以使用一些已经准备好的静态对象或来自.Net类库的组件,也可以是绑定到先前作为资源创建的对象。

    1. "instrument" ExchangeID="SHSE" InstrumentID="600000" InstrumentName="浦发银行">
    2. "{Binding Source={x:Static SystemFonts.IconFontFamily}, Path=Source}"/>
    3. "{Binding Source={x:Static local:MainWindow.StaticString}}"/>
    4. "{Binding Source={StaticResource instrument}, Path=ExchangeID}"/>

    RelativeSource属性

    通过RelativeSource属性可根据相对于目标对象的关系指向源对象。例如,可使用RelativeSource属性将元素绑定到自身或其父元素。RelativeSource 对象查找有四种模式,通过Mode 属性设置:

    Self:表达式绑定到同一元素的另一个属性上

    "{Binding RelativeSource={RelativeSource Mode=Self}, Path=Foreground, StringFormat={}{0}}"/>

    FindAncestor:表达式绑定到父元素。WPF将查找元素树,直至发现期望的父元素。为了指定父元素,还必须设置AncestorType 属性以指示希望查找的父元素的类型。此外,还可以用AncestorLevel 属性略过发现的一定数量的特定元素。例如,当在一棵树中查找时,如果希望绑定到第三个ListBoxItem 类型的元素,应当使用如下设置—— AncestorType = {x:Type ListBoxItem} 并设置 AncestorLevel = 3,从而略过前两个ListBoxItem 元素。默认情况下,AncestorLevel 属性设置为1,并在找到第一个匹配的元素时停止查找

    1. "BindingTextBlockStackPanel">
    2. "{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type StackPanel}}, Path=Name}"/>

    PreviousData:表达式绑定到数据绑定列表中的前一个数据项。在列表项中会使用这种模式

    1. "{Binding Path=Instruments}">
    2. "Horizontal" Margin="2">
    3. "{Binding ExchangeID}" />
    4. "{Binding Path=InstrumentID, RelativeSource={RelativeSource Mode=PreviousData}}" Foreground="Red" Margin="5,0,0,0"/>

    TemplateParent:表达式绑定到应用模板的元素。只有当绑定位于控件模板或数据模板内部时,这种模式才能工作。

    1. "Button">
    2. "{Binding RelativeSource={RelativeSource Mode=TemplatedParent}, Path=Background}"/>
    3. "Center" HorizontalAlignment="Center"/>

    DataContext属性

    在某些情况下,会将大量元素绑定到同一个对象。对于这种情况,使用DataContext 属性一次性定义绑定源会更清晰,也更灵活。

    1. "{x:Static SystemFonts.IconFontFamily}">
    2. "{Binding Path=Source}"/>
    3. "{Binding Path=LineSpacing}"/>
    4. "{Binding Path=FamilyTypefaces[0].Style}"/>
    5. "{Binding Path=FamilyTypefaces[0].Weight}"/>

    完整代码如下:

    MainWindow.xaml

    1. "TestElementBinding.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:TestElementBinding"
    7. mc:Ignorable="d"
    8. Title="MainWindow" Height="450" Width="800">
    9. "instrument" ExchangeID="SHSE" InstrumentID="600000" InstrumentName="浦发银行">
    10. "sliderFontSize" Minimum="1" Maximum="40" Value="10" TickFrequency="1" />
    11. "textBlockFontSize" FontSize="{Binding ElementName=sliderFontSize, Path=Value, Mode=TwoWay}" Text="Simple Text"/>
    12. "textBlockFontSize2" Text="Simple Text"/>
    13. "txtContent" Text="{Binding ElementName=textBlockFontSize, Path=FontSize, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, Delay=500}"/>
    14. "txtContent2" Text="{Binding ElementName=sliderFontSize, Path=Value, Mode=TwoWay, UpdateSourceTrigger=Explicit}"/>
    15. "{Binding ElementName=sliderFontSize, Path=Value, Mode=TwoWay}" Text="{Binding ElementName=txtContent, Path=Text}"/>
    16. "{Binding Source={x:Static SystemFonts.IconFontFamily}, Path=Source}"/>
    17. "{Binding Source={x:Static local:MainWindow.StaticString}}"/>
    18. "{Binding Source={StaticResource instrument}, Path=ExchangeID}"/>
    19. "BindingTextBlockStackPanel">
    20. "{Binding RelativeSource={RelativeSource Mode=Self}, Path=Foreground, StringFormat={}{0}}"/>
    21. "{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type StackPanel}}, Path=Name}"/>
    22. "{Binding Path=Instruments}">
    23. "Horizontal" Margin="2">
    24. "{Binding ExchangeID}" />
    25. "{Binding Path=InstrumentID, RelativeSource={RelativeSource Mode=PreviousData}}" Foreground="Red" Margin="5,0,0,0"/>
    26. "Button">
    27. "{Binding RelativeSource={RelativeSource Mode=TemplatedParent}, Path=Background}"/>
    28. "Center" HorizontalAlignment="Center"/>
    29. "{x:Static SystemFonts.IconFontFamily}">
    30. "{Binding Path=Source}"/>
    31. "{Binding Path=LineSpacing}"/>
    32. "{Binding Path=FamilyTypefaces[0].Style}"/>
    33. "{Binding Path=FamilyTypefaces[0].Weight}"/>

    MainWindow.xaml.cs

    1. using System;
    2. using System.Collections.Generic;
    3. using System.Collections.ObjectModel;
    4. using System.ComponentModel;
    5. using System.Linq;
    6. using System.Runtime.CompilerServices;
    7. using System.Text;
    8. using System.Threading.Tasks;
    9. using System.Windows;
    10. using System.Windows.Controls;
    11. using System.Windows.Data;
    12. using System.Windows.Documents;
    13. using System.Windows.Input;
    14. using System.Windows.Media;
    15. using System.Windows.Media.Imaging;
    16. using System.Windows.Navigation;
    17. using System.Windows.Shapes;
    18. namespace TestElementBinding;
    19. public class ViewModelBase : INotifyPropertyChanged
    20. {
    21. public event PropertyChangedEventHandler? PropertyChanged;
    22. protected virtual void OnPropertyChanged([CallerMemberName] string? propertyName = null)
    23. {
    24. PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    25. }
    26. protected virtual bool SetProperty<T>(ref T member, T value, [CallerMemberName] string? propertyName = null)
    27. {
    28. if (EqualityComparer.Default.Equals(member, value))
    29. {
    30. return false;
    31. }
    32. member = value;
    33. OnPropertyChanged(propertyName);
    34. return true;
    35. }
    36. }
    37. public class InstrumentViewModel : ViewModelBase
    38. {
    39. private string _exchangeID = string.Empty;
    40. private string _instrumentID = string.Empty;
    41. private string _instrumentName = string.Empty;
    42. public string ExchangeID { get => _exchangeID; set => SetProperty(ref _exchangeID, value); }
    43. public string InstrumentID { get => _instrumentID; set => SetProperty(ref _instrumentID, value); }
    44. public string InstrumentName { get => _instrumentName; set => SetProperty(ref _instrumentName, value); }
    45. }
    46. public partial class MainWindow : Window
    47. {
    48. public MainWindow()
    49. {
    50. InitializeComponent();
    51. InitInstruments();
    52. BindingTextBlockStackPanel.DataContext = this;
    53. textBlockFontSize2.SetBinding(TextBlock.FontSizeProperty, new Binding("Value") { ElementName = "sliderFontSize", Mode = BindingMode.TwoWay });
    54. }
    55. public static string StaticString { get; set; } = "Static String";
    56. public ObservableCollection Instruments { get; set; } = new ObservableCollection ();
    57. public void InitInstruments()
    58. {
    59. Instruments.Add(new InstrumentViewModel() { ExchangeID = "SHSE", InstrumentID = "601155", InstrumentName = "新城控股" });
    60. Instruments.Add(new InstrumentViewModel() { ExchangeID = "SHSE", InstrumentID = "600036", InstrumentName = "招商银行" });
    61. Instruments.Add(new InstrumentViewModel() { ExchangeID = "SHSE", InstrumentID = "600266", InstrumentName = "城建发展" });
    62. Instruments.Add(new InstrumentViewModel() { ExchangeID = "SHSE", InstrumentID = "600837", InstrumentName = "海通证券" });
    63. Instruments.Add(new InstrumentViewModel() { ExchangeID = "SHSE", InstrumentID = "601668", InstrumentName = "中国建筑" });
    64. Instruments.Add(new InstrumentViewModel() { ExchangeID = "SZSE", InstrumentID = "000002", InstrumentName = "万科A" });
    65. Instruments.Add(new InstrumentViewModel() { ExchangeID = "SZSE", InstrumentID = "000001", InstrumentName = "平安银行" });
    66. Instruments.Add(new InstrumentViewModel() { ExchangeID = "SZSE", InstrumentID = "000623", InstrumentName = "吉林敖东" });
    67. Instruments.Add(new InstrumentViewModel() { ExchangeID = "SZSE", InstrumentID = "002739", InstrumentName = "万达电影" });
    68. Instruments.Add(new InstrumentViewModel() { ExchangeID = "SZSE", InstrumentID = "300642", InstrumentName = "透景生命" });
    69. }
    70. private void Button_Click(object sender, RoutedEventArgs e)
    71. {
    72. Binding binding = BindingOperations.GetBinding(textBlockFontSize, TextBox.FontSizeProperty);
    73. MessageBox.Show("Bound " + binding.Path.Path + " to source element " + binding.ElementName);
    74. //BindingExpression expression = BindingOperations.GetBindingExpression(textBlockFontSize, TextBlock.FontSizeProperty);
    75. BindingExpression expression = textBlockFontSize.GetBindingExpression(TextBlock.FontSizeProperty);
    76. MessageBox.Show("Bound " + expression.ResolvedSourcePropertyName + " with data " + ((Slider)expression.ResolvedSource).Value);
    77. }
    78. private void UpdateSourceButton_Click(object sender, RoutedEventArgs e)
    79. {
    80. BindingExpression expression = txtContent2.GetBindingExpression(TextBox.TextProperty);
    81. expression.UpdateSource();
    82. }
    83. }

  • 相关阅读:
    postgresql 表、索引的膨胀率监控
    用Java实现贪吃蛇小游戏
    python 之 矩阵相关操作
    Linux 环境安装【jdk、Tomcat、Docker、Maven、Kafka、Redis等】
    算法刷题记录-图(LeetCode)
    开始学习React——跟着官网做井字棋
    技术管理 - 学习/实践
    我国首个发酵饲料原料行标准修订发布 国稻种芯现代饲草规划
    信息学奥赛一本通 1361:产生数(Produce)
    Spring Boot2.5 使用 Spring Data
  • 原文地址:https://blog.csdn.net/xunmeng2002/article/details/132695692