绑定: DataContextChanged, UpdateSourceTrigger, 对绑定的数据做自定义转换

介绍
背水一战 Windows 10 之 绑定

  • DataContextChanged - FrameworkElement 的 DataContext 发生变化时触发的事件
  • UpdateSourceTrigger - 数据更新的触发方式
  • 对绑定的数据做自定义转换



示例
1、演示 DataContextChanged 的用法
Bind/DataContextChanged.xaml

复制代码
<Page
    x:Class="Windows10.Bind.DataContextChanged"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:Windows10.Bind"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <Grid Background="Transparent">

        <StackPanel Margin="10 0 10 10">

            <TextBlock Name="lblMsg" Margin="5" />

            <Button x:Name="btnChange" Content="改变 listBox 的数据上下文" Click="btnChange_Click" Margin="5" />

            <ListBox x:Name="listBox" ItemsSource="{Binding}" DataContextChanged="listBox_DataContextChanged" Background="Orange" Margin="5" />

        </StackPanel>
    </Grid>
</Page>
复制代码

Bind/DataContextChanged.xaml.cs

复制代码
/*
 * DataContextChanged - FrameworkElement 的 DataContext 发生变化时触发的事件
 */

using System;
using System.Collections.Generic;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

namespace Windows10.Bind
{
    public sealed partial class DataContextChanged : Page
    {
        public DataContextChanged()
        {
            this.InitializeComponent();

            this.Loaded += DataContextChanged_Loaded;
        }

        private void DataContextChanged_Loaded(object sender, RoutedEventArgs e)
        {
            // 指定数据上下文
            listBox.DataContext = new List<string> { "a", "b", "c" };
        }

        private void btnChange_Click(object sender, RoutedEventArgs e)
        {
            // 修改数据上下文
            listBox.DataContext = new List<string> { "a", "b", new Random().Next(0, 1000).ToString().PadLeft(3, '0') };
        }

        private void listBox_DataContextChanged(FrameworkElement sender, DataContextChangedEventArgs args)
        {
            /*
             * FrameworkElement.DataContextChanged - 数据上下文发生改变后触发的事件
             */

            // 数据上下文发生改变后
            lblMsg.Text = "数据上下文发生改变:" + DateTime.Now.ToString("hh:mm:ss");

        }
    }
}
复制代码


2、演示 UpdateSourceTrigger 的用法
Bind/UpdateSourceTrigger.xaml

复制代码
<Page
    x:Class="Windows10.Bind.UpdateSourceTrigger"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:Windows10.Bind"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <Grid Background="Transparent">

        <StackPanel Margin="10 0 10 10">

            <TextBlock Name="lblMsg" Foreground="Orange" Margin="5" />

            <!--
                UpdateSourceTrigger - 数据更新的触发方式
                    Default - 失去焦点后触发
                    PropertyChanged - 属性值发生改变后触发
                    Explicit - 需要通过 BindingExpression.UpdateSource() 显示触发
            -->

            <TextBox Text="{Binding Text, Mode=TwoWay, ElementName=lblMsg, UpdateSourceTrigger=Default}" Margin="5" />
            <TextBox Text="{Binding Text, Mode=TwoWay, ElementName=lblMsg, UpdateSourceTrigger=PropertyChanged}" Margin="5" />
            <TextBox Name="txtExplicit" Text="{Binding Text, Mode=TwoWay, ElementName=lblMsg, UpdateSourceTrigger=Explicit}" Margin="5" />

            <Button Name="btnBinding" Content="显示触发更新" Click="btnBinding_Click" Margin="5" />

        </StackPanel>
    </Grid>
</Page>
复制代码

Bind/UpdateSourceTrigger.xaml.cs

复制代码
/*
 * UpdateSourceTrigger - 数据更新的触发方式
 *     Default - 失去焦点后触发
 *     PropertyChanged - 属性值发生改变后触发
 *     Explicit - 需要通过 BindingExpression.UpdateSource() 显示触发
 */

using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Data;

namespace Windows10.Bind
{
    public sealed partial class UpdateSourceTrigger : Page
    {
        public UpdateSourceTrigger()
        {
            this.InitializeComponent();
        }

        private void btnBinding_Click(object sender, RoutedEventArgs e)
        {
            // 显示触发 txtExplicit 的数据更新
            BindingExpression be = txtExplicit.GetBindingExpression(TextBox.TextProperty);
            be.UpdateSource();
        }
    }
}
复制代码


3、演示如何对绑定的数据做自定义转换
Bind/BindingConverter.xaml

复制代码
<Page
    x:Class="Windows10.Bind.BindingConverter"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:Windows10.Bind"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <Grid Background="Transparent">
        <StackPanel Margin="10 0 10 10">

            <!--
                配置 IValueConverter 资源
            -->
            <StackPanel.Resources>
                <local:IntegerLetterConverter x:Key="IntegerLetterConverter"/>
            </StackPanel.Resources>


            <Slider Name="slider1" Minimum="97" Maximum="122" Value="1" Width="300" Background="White" HorizontalAlignment="Left" Margin="5" />
            <!--
                演示如何使用 Binding 的 Converter, ConverterParameter, ConverterLanguage
                注:ConverterParameter 和 ConverterLanguage 不支持绑定,只能配置为一个静态的值(但是在 C# 端可以实现一些在 xaml 中无法实现的特性,详见后面的例子)
            -->
            <TextBox Name="textBox1" Width="300" HorizontalAlignment="Left" Margin="5"
                     Text="{Binding ElementName=slider1, Path=Value, Mode=TwoWay,
                                    Converter={StaticResource IntegerLetterConverter},
                                    ConverterParameter=param, 
                                    ConverterLanguage=zh}" />


            <Slider Name="slider2" Minimum="97" Maximum="122" Value="1" Width="300" Background="White" HorizontalAlignment="Left" Margin="5" />
            <!--
                在 C# 端使用 Binding 的 Converter, ConverterParameter, ConverterLanguage
            -->
            <TextBox Name="textBox2" Width="300" HorizontalAlignment="Left" Margin="5" />

            
            <TextBlock Name="lblMsg" TextWrapping="Wrap" />

        </StackPanel>
    </Grid>
</Page>
复制代码

Bind/BindingConverter.xaml.cs

复制代码
/*
 * 演示如何对绑定的数据做自定义转换
 */

using System;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Data;

namespace Windows10.Bind
{
    public sealed partial class BindingConverter : Page
    {
        public BindingConverter()
        {
            this.InitializeComponent();

            this.Loaded += BindingConverter_Loaded;
        }

        private void BindingConverter_Loaded(object sender, RoutedEventArgs e)
        {
            // 实例化 Binding 对象
            Binding binding = new Binding()
            {
                ElementName = nameof(slider2),
                Path = new PropertyPath(nameof(Slider.Value)),
                Mode = BindingMode.TwoWay, // 默认是 OneWay 的
                Converter = new IntegerLetterConverter(),
                ConverterParameter = lblMsg, // 将 ConverterParameter 设置为一个指定的控件,这个在 xaml 中实现不了,但是可以在 C# 端实现
                ConverterLanguage = "zh"
            };

            // 将目标对象的目标属性与指定的 Binding 对象关联
            BindingOperations.SetBinding(textBox2, TextBox.TextProperty, binding);
        }
    }



    // 自定义一个实现了 IValueConverter 接口的类,用于对绑定的数据做自定义转换
    public sealed class IntegerLetterConverter : IValueConverter
    {
        /// <summary>
        /// 正向转换器。将值从数据源传给绑定目标时,数据绑定引擎会调用此方法
        /// </summary>
        /// <param name="value">转换之前的值</param>
        /// <param name="targetType">转换之后的数据类型</param>
        /// <param name="parameter">转换器所使用的参数(它是通过 Binding 的 ConverterParameter 传递过来的)</param>
        /// <param name="language">转换器所使用的区域信息(它是通过 Binding 的 ConverterLanguage 传递过来的)</param>
        /// <returns>转换后的值</returns>
        public object Convert(object value, Type targetType, object parameter, string language)
        {
            if (parameter != null && parameter.GetType() == typeof(TextBlock))
            {
                ((TextBlock)parameter).Text = $"value: {value}, targetType: {targetType}, parameter: {parameter}, language: {language}";
            }

            int v = (int)(double)value;
            return (char)v;
        }

        /// <summary>
        /// 反向转换器。将值从绑定目标传给数据源时,数据绑定引擎会调用此方法
        /// </summary>
        /// <param name="value">转换之前的值</param>
        /// <param name="targetType">转换之后的数据类型</param>
        /// <param name="parameter">转换器所使用的参数(它是通过 Binding 的 ConverterParameter 传递过来的)</param>
        /// <param name="language">转换器所使用的区域信息(它是通过 Binding 的 ConverterLanguage 传递过来的)</param>
        /// <returns>转换后的值</returns>
        public object ConvertBack(object value, Type targetType, object parameter, string language)
        {
            if (parameter != null && parameter.GetType() == typeof(TextBlock))
            {
                ((TextBlock)parameter).Text = $"value: {value}, targetType: {targetType}, parameter: {parameter}, language: {language}";
            }

            int v = ((string)value).ToCharArray()[0];
            return v;
        }
    }
}
复制代码

转载于:https://www.cnblogs.com/ansen312/p/5913444.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在 WPF 中,自定义的 PasswordBox 控件默认情况下是不支持双向的。但是我们可以通过一些技巧来实现 Password 属性的双向。 首先,我们可以创建一个附加属性(Attached Property),并将其附加到 PasswordBox 控件上。这个附加属性将作为一个中间层,用于实现双向。 以下是一个示例代码,演示如何实现双向: 1. 首先,在你的项目中创建一个类,命名为 PasswordBoxHelper(或者其他你喜欢的名称): ```csharp public static class PasswordBoxHelper { public static readonly DependencyProperty PasswordProperty = DependencyProperty.RegisterAttached("Password", typeof(string), typeof(PasswordBoxHelper), new FrameworkPropertyMetadata(string.Empty, OnPasswordPropertyChanged)); public static string GetPassword(DependencyObject d) { return (string)d.GetValue(PasswordProperty); } public static void SetPassword(DependencyObject d, string value) { d.SetValue(PasswordProperty, value); } private static void OnPasswordPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { if (d is PasswordBox passwordBox) { passwordBox.PasswordChanged -= PasswordBox_PasswordChanged; passwordBox.PasswordChanged += PasswordBox_PasswordChanged; } } private static void PasswordBox_PasswordChanged(object sender, RoutedEventArgs e) { if (sender is PasswordBox passwordBox) { SetPassword(passwordBox, passwordBox.Password); } } } ``` 2. 然后,在你的 XAML 文件中使用这个附加属性来 Password 属性,示例如下: ```xml <PasswordBox local:PasswordBoxHelper.Password="{Binding MyPassword, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" /> ``` 这里的 `local` 是你在 XAML 文件开头添加的命名空间引用,指向你定义的 PasswordBoxHelper 类所在的命名空间。 3. 最后,在你的 ViewModel 或者代码中声明一个名为 MyPassword 的属性,用于实际存储密码值: ```csharp private string _myPassword; public string MyPassword { get { return _myPassword; } set { if (_myPassword != value) { _myPassword = value; OnPropertyChanged(nameof(MyPassword)); } } } ``` 这样,当用户在 PasswordBox 中输入密码时,双向会自动更新 MyPassword 属性的值。同样地,当 MyPassword 属性的值改变时,也会自动更新到 PasswordBox 控件中。 希望这个示例能够帮助到你!如果你有任何其他问题,请随时提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值