考慮這個(gè)非常簡(jiǎn)單的例子,我有一個(gè)像這樣的 UserControl:用戶(hù)控件 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)); }}所以控件只顯示一個(gè) TextBlock 并且每 5 秒增加一次計(jì)數(shù)器。然后我當(dāng)然有一個(gè)消費(fèi)者:是的,所以 main 在代碼背后有一個(gè)計(jì)數(shù)器,每秒更新一個(gè)屬性。XAML 有 2 個(gè) UserControl 實(shí)例。一種具有OneWay綁定,一種具有TwoWay綁定。我在這里看到的是,當(dāng)“SomeControl.cs”中的計(jì)數(shù)器更新時(shí),第一個(gè) UserControl (OneWay) 的綁定被破壞。帶有 TwoWay 的那個(gè)不斷更新。這是設(shè)計(jì)使然(以及為什么)?更重要的是,如果我需要更新我的 UserControls 中的屬性,我將如何在我的示例中執(zhí)行此操作 - 以支持 OneWay 綁定?請(qǐng)注意,我真的對(duì)本示例中的 TwoWay 綁定不感興趣,因?yàn)樗鼤?huì)更新“MySource”,這不是我想要的!
更新控件屬性會(huì)破壞 OneWay 綁定?
慕田峪9158850
2021-11-28 19:31:19