DirectionalBinding绑定方向

实现效果:

  1. 见图示说明
  2. 点击更新租金后获取绑定数据进行属性更新
  3. 更改其中一项值进行租金重新结算

clipboard.png
clipboard.png
实践:

  1. Binding.Mode 属性使用
  2. NotifyOnTargetUpdated引发 TargetUpdated 事件

代码:
数据上下文的绑定源

<Grid.DataContext>
    <Binding Source="{StaticResource IncomeDataSource}"/>
</Grid.DataContext>

绑定目标通知更新NotifyOnTargetUpdated

<TextBlock Grid.Row="1" Grid.Column="1" Name="RentText"
    Text="{Binding Path=Rent, Mode=OneWay, NotifyOnTargetUpdated=True}"
    TargetUpdated="OnTargetUpdated"/>

获取绑定数据类型引用并进行属性重新设置

private void OnRentRaise(object sender, RoutedEventArgs args)
{
    // Update bills
    var random = new Random();
    double i = random.Next(10);
    var bindingExpression =
        BindingOperations.GetBindingExpression(SavingsText, TextBlock.TextProperty);
    var sourceData = (NetIncome) bindingExpression.DataItem;
    sourceData.Rent = (int) ((1 + i/100)*sourceData.Rent);
}

绑定目标更新方法:

private void OnTargetUpdated(object sender, DataTransferEventArgs args)
{
    // Handle event
    var fe = sender as FrameworkElement;
    infoText.Text = "";
    infoText.Text += args.Property.Name + " property of a " + args.Property.OwnerType.Name;
    infoText.Text += " element (";
    infoText.Text += fe.Name;
    infoText.Text += ") updated...";
    infoText.Text += DateTime.Now.ToLongDateString();
    infoText.Text += " at ";
    infoText.Text += DateTime.Now.ToLongTimeString();
}

扩展:

  1. 当值从绑定源传输到绑定目标时发生 TargetUpdated 事件,但只针对 NotifyOnTargetUpdated 值设置为 true 的绑定。
  2. 当值从目标传输到源时发生 SourceUpdated 事件,但只针对 NotifyOnSourceUpdated 值设置为 true 的绑定。
  3. DataTransferEventArgs 类:封装数据传输事件的参数。

李志玮
22 声望34 粉丝

求索~~


引用和评论

0 条评论