为了账号安全,请及时绑定邮箱和手机立即绑定

更新控件属性会破坏 OneWay 绑定?

更新控件属性会破坏 OneWay 绑定?

C#
慕田峪9158850 2021-11-28 19:31:19
考虑这个非常简单的例子,我有一个像这样的 UserControl:用户控件 XAML:<UserControl x:Class="BindingTest.SomeControl"             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"             x:Name="SomeControlElement">    <Grid>        <TextBlock Text="{Binding ElementName=SomeControlElement, Path=Counter}" />    </Grid></UserControl>背后的代码:using System;using System.Windows;using System.Windows.Controls;using System.Windows.Threading;namespace BindingTest{     public partial class SomeControl : UserControl    {        public SomeControl()        {            InitializeComponent();            var timer = new DispatcherTimer();            timer.Interval = new TimeSpan(0, 0, 5);            timer.Tick += (s, e) => Counter = Counter + 1;            timer.Start();        }        public int Counter        {            get { return (int)GetValue(CounterProperty); }            set { SetValue(CounterProperty, value); }        }        public static readonly DependencyProperty CounterProperty = DependencyProperty.Register(nameof(Counter), typeof(int), typeof(SomeControl), new PropertyMetadata(0));    }}所以控件只显示一个 TextBlock 并且每 5 秒增加一次计数器。然后我当然有一个消费者:是的,所以 main 在代码背后有一个计数器,每秒更新一个属性。XAML 有 2 个 UserControl 实例。一种具有OneWay绑定,一种具有TwoWay绑定。我在这里看到的是,当“SomeControl.cs”中的计数器更新时,第一个 UserControl (OneWay) 的绑定被破坏。带有 TwoWay 的那个不断更新。这是设计使然(以及为什么)?更重要的是,如果我需要更新我的 UserControls 中的属性,我将如何在我的示例中执行此操作 - 以支持 OneWay 绑定?请注意,我真的对本示例中的 TwoWay 绑定不感兴趣,因为它会更新“MySource”,这不是我想要的!
查看完整描述

1 回答

?
猛跑小猪

TA贡献1858条经验 获得超8个赞

这是设计使然。当您将所谓的本地值分配给依赖项属性时,先前分配的 OneWay Binding 将被替换。双向绑定保持活动状态并更新其源属性。

但是,有一个解决方法。不要设置本地值,而是设置“当前值”。代替

timer.Tick += (s, e) => Counter = Counter + 1;

timer.Tick += (s, e) => SetCurrentValue(CounterProperty, Counter + 1);


查看完整回答
反对 回复 2021-11-28
  • 1 回答
  • 0 关注
  • 215 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信