有没有办法可以使用这个依赖属性? WPF C#

问题描述 投票:0回答:1

我试图在自定义控件中设置 SKQuantitySpinEdit 父类的增量属性,但无法这样做!

  ControlTemplate spinOptLegQuantityTemplate = (ControlTemplate)(grdMultiFills.FindResource("OptLegQuantitySpinEditEntry") as SKControlTemplate).Clone();
                FrameworkElementFactory gridOptLegQuantityControlElement = new FrameworkElementFactory(typeof(SKQuantitySpinEdit));
                spinOptLegQuantityTemplate.VisualTree = gridOptLegQuantityControlElement;

Binding optLegQuantityControlBinding = new Binding(string.Format(BindingRowData_Row + BindingOptLegQuantity, optIndex)) { Mode = BindingMode.TwoWay };
                gridOptLegQuantityControlElement.SetValue(SKQuantitySpinEdit.EditValueProperty, optLegQuantityControlBinding);
                gridOptLegQuantityControlElement.SetValue(SKQuantitySpinEdit.NameProperty, string.Format("OptLegQuantityControl_{0}", count));
                gridOptLegQuantityControlElement.AddHandler(SKQuantitySpinEdit.EditValueChangedEvent, new EditValueChangedEventHandler(m_optLegQuantityChange_EditValueChanged));
                gridOptLegQuantityControlElement.AddHandler(SKQuantitySpinEdit.LoadedEvent, new RoutedEventHandler(LegQtyControl_Loaded));

所以我做了这样的增量属性 - 依赖属性:

public int Increment
        {
            get { return (int)GetValue(IncrementProperty); }
            set { SetValue(IncrementProperty, value); }
        }

        public static readonly DependencyProperty IncrementProperty =
            DependencyProperty.Register("Increment", typeof(int), typeof(SKSingleSpinner), new PropertyMetadata(0));

并尝试像这样设置它的值

gridOptLegQuantityControlElement.SetValue(SKSingleSpinner.IncrementProperty , 1);

但它不起作用! 一定是什么问题?

c# wpf xaml dependency-properties
1个回答
0
投票

为什么使用

FrameworkElementFactory
?对于你的情况来说这是完全多余的。它用于例如构建框架模板。即使它是合理的,
FrameworkElementFactory
也已被弃用,不应再使用。您可以使用 XAML(您首先应该这样做,因为它在许多方面都是最佳解决方案)或使用
System.Xaml.XamlReader

返回的模板资源的转换也不是必需的。在将其转换为基本类型 (

SKControlTemplate
) 之前,您不必将其转换为原始类型 (
ControlTemplate
)。根据所需的类型 API 或基于依赖关系设计规则,使用其中之一或。在这种情况下,转换为 ControlTemplate
 就足够了。

因为您的

ControlTemplate

 已经定义(并且不必使用 C# 手动构建),您可以按如下方式简化代码:

var spinOptLegQuantityTemplate = (ControlTemplate)grdMultiFills.FindResource("OptLegQuantitySpinEditEntry"); var quantitySpinEditControl = new SKQuantitySpinEdit(); quantitySpinEditControl.Template = spinOptLegQuantityTemplate; // Set the dependency property using the CLR wrapper quantitySpinEditControl.Increment = 1;
现在,依赖属性声明为错误的类型。换句话说,

SKQuantitySpinEdit

 没有定义 
IncrementProperty

相反,为

SKSingleSpinner

:
声明了依赖属性

DependencyProperty.Register( "Increment", typeof(int), typeof(SKSingleSpinner), // <== Wrong owner new PropertyMetadata(0));
这可能是一个错字。

© www.soinside.com 2019 - 2024. All rights reserved.