考虑这个非常简单的例子,我有一个像这样的 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”,这不是我想要的!
猛跑小猪
相关分类