问题描述
如果你有一个ColorIicker,其Color使用{x:Bind}和模式TwoWay绑定到一个支持DependencyProperty,你会得到一个StackOverflowException。
If you have a ColorPicker whose Color is bound using {x:Bind} and mode TwoWay to a backing DependencyProperty, you get a StackOverflowException.
这将是一个相当常见的场景,有人想将ColorPicker的Color绑定到'支持'DependencyProperty,可能是在Page或ContentDialog中。
This is going to be a fairly common scenario, where someone wants to bind the ColorPicker's Color to a 'backing' DependencyProperty, perhaps in a Page or a ContentDialog.
问题是Color类型的DependencyProperty显然没有我不知道如何比较两种颜色,即使(至少在C#中),如果两个Color实例具有相同的A,R,G和B值,则以下所有都返回true:
The problem is that a DependencyProperty of type Color apparently doesn't know how to compare two Colors, even though (in C#, at least), if two Color instances have the same A, R, G and B values, all of the following return true:
color1 == color2
color1.Equals(color2)
Object.Equals(color1, color2)
另一方面,如果在包含的类上实现INotifyPropertyChanged并使用简单的CLR属性作为"支持"颜色,如下所示:
If, on the other hand, you implement INotifyPropertyChanged on your containing class and use a simple CLR property for the 'backing' color, like this:
public Color SelectedColor
{
get { return m_selectedColor; }
set
{
if (m_selectedColor != value)
{
m_selectedColor = value;
OnPropertyChanged(nameof(SelectedColor));
}
}
}
然后它运作正常。
then it works just fine.
推荐答案
using System;
using Windows.UI;
using Windows.UI.Xaml;
namespace ColorPickerBug
{
public class BadColorDP : DependencyObject
{
public BadColorDP()
{
// This is NOT a change from the DP's default value, but it will display
// 'OnMyColorPropertyChanged' in the Debug window.
MyColor = Colors.Red;
// So will these (the first one correctly, the second on incorrectly).
MyColor = Colors.Yellow;
MyColor = Colors.Yellow;
}
public Color MyColor
{
get { return (Color)GetValue(MyColorProperty); }
set { SetValue(MyColorProperty, value); }
}
private static void OnMyColorPropertyChanged(DependencyObject dobj, DependencyPropertyChangedEventArgs args)
{
System.Diagnostics.Debug.WriteLine("OnMyColorPropertyChanged");
}
public static readonly DependencyProperty MyColorProperty =
DependencyProperty.Register("MyColor",
typeof(Color),
typeof(BadColorDP),
new PropertyMetadata(Colors.Red, OnMyColorPropertyChanged));
}
}
这是导致TwoWay绑定在控件和DP之间来回"反弹"的原因 - DP认为每个 b 每次更改都值得通知,即使这不是"真正的"更改。
This is what causes the TwoWay binding to 'bounce' back and forth between the control and the DP -- the DP thinks thatevery change is worthy of notification, even if it's not a 'real' change.
这篇关于[RS3:1709] Fall Creator的更新:ColorPicker.Color不能以两种方式绑定到DependencyProperty的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!