WPF Style BasedOn Loses Setters?
WPF Style BasedOn Loses Setters?
我正在代码隐藏中创建一种样式,它是 "BasedOn" 相同 TargetType 的全局资源样式。新样式具有与原始样式相同的所有属性,外加一项独有的附加 Setter。似乎 Setters 没有复制到我的新样式中,迫使我遍历所有原始 Setters 并将它们作为新的 Setters 添加到我的样式中。有没有更好的方法来完成此行为?
Style defaultStyle = Application.Current.FindResource("NumericFieldStyle") as Style;
Style decimalStyle = new Style(typeof(XamMaskedEditor), defaultStyle);
// No setters in decimalStyle? There were 6 in defaultStyle
foreach (SetterBase setter in defaultStyle.Setters)
decimalStyle.Setters.Add(setter);
Style
继承并不像您猜想的那样起作用。当您设置 Style
的 BasedOn
属性 时,它不会成为父样式的克隆。相反,应用父样式(如果需要则递归),然后应用子样式。
如果您注释掉 setter 循环并在调试器中查看 defaultStyle
,您只会看到您明确添加的 setter,但是 defaultStyle.BasedOn
将扩展为 NumericFieldStyle
-- 在那里您会看到缺少的 setter。他们将被应用。
MSDN says "the new style will inherit the values of the original style that are not explicitly redefined in the new style",但如您所见,这是描述实际发生情况的一种有点油嘴滑舌的方式。
我正在代码隐藏中创建一种样式,它是 "BasedOn" 相同 TargetType 的全局资源样式。新样式具有与原始样式相同的所有属性,外加一项独有的附加 Setter。似乎 Setters 没有复制到我的新样式中,迫使我遍历所有原始 Setters 并将它们作为新的 Setters 添加到我的样式中。有没有更好的方法来完成此行为?
Style defaultStyle = Application.Current.FindResource("NumericFieldStyle") as Style;
Style decimalStyle = new Style(typeof(XamMaskedEditor), defaultStyle);
// No setters in decimalStyle? There were 6 in defaultStyle
foreach (SetterBase setter in defaultStyle.Setters)
decimalStyle.Setters.Add(setter);
Style
继承并不像您猜想的那样起作用。当您设置 Style
的 BasedOn
属性 时,它不会成为父样式的克隆。相反,应用父样式(如果需要则递归),然后应用子样式。
如果您注释掉 setter 循环并在调试器中查看 defaultStyle
,您只会看到您明确添加的 setter,但是 defaultStyle.BasedOn
将扩展为 NumericFieldStyle
-- 在那里您会看到缺少的 setter。他们将被应用。
MSDN says "the new style will inherit the values of the original style that are not explicitly redefined in the new style",但如您所见,这是描述实际发生情况的一种有点油嘴滑舌的方式。