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

考虑这个非常简单的例子,我有一个像这样的 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”,这不是我想要的!


慕田峪9158850
浏览 216回答 1
1回答

猛跑小猪

这是设计使然。当您将所谓的本地值分配给依赖项属性时,先前分配的 OneWay Binding 将被替换。双向绑定保持活动状态并更新其源属性。但是,有一个解决方法。不要设置本地值,而是设置“当前值”。代替timer.Tick&nbsp;+=&nbsp;(s,&nbsp;e)&nbsp;=>&nbsp;Counter&nbsp;=&nbsp;Counter&nbsp;+&nbsp;1;和timer.Tick&nbsp;+=&nbsp;(s,&nbsp;e)&nbsp;=>&nbsp;SetCurrentValue(CounterProperty,&nbsp;Counter&nbsp;+&nbsp;1);
打开App,查看更多内容
随时随地看视频慕课网APP