【问题标题】:How to assign a property of type Control in XAML - error如何在 XAML 中分配 Control 类型的属性 - 错误
【发布时间】:2013-07-14 20:53:17
【问题描述】:

我有一个带有 Control 类型属性的 WPF 用户控件,以便将它与另一个控件(通常是文本框)相关联,并将按键发送到该控件。 我可以在 XAML 中分配这个属性,它会在运行时编译并工作

但 IDE 显示错误“38 方法或操作未实现”。在 TargetControl 分配上。

<my:NumericButtonsControl 
 x:Name="NumericButtons" 
 TargetControl="{x:Reference Name=DataEntryTextBox}" />

有问题的用户控制代码如下所示:

public partial class NumericButtonsControl : UserControl
{
    private Control _TargetControl;

    public Control TargetControl
    {
        get 
        {
            return _TargetControl;
        }
        set
        {
            _TargetControl = value;
        }
    }
 }

【问题讨论】:

    标签: c# .net wpf xaml user-controls


    【解决方案1】:

    当您编写 WPF 应用程序时,您可能希望避免使用 x:Reference,因为它是 XAML 2009 的一个功能,仅适用于松散的 XAML。

    或者,您可以使用绑定及其ElementName 属性。但要使其正常工作,您需要将 TargetControl 设为依赖属性。然后它看起来像这样:

    C#

    public Control TargetControl
    {
        get { return (Control)this.GetValue(TargetControlProperty); }
        set { this.SetValue(TargetControlProperty, value); } 
    }
    
    public static readonly DependencyProperty TargetControlProperty =
        DependencyProperty.Register("TargetControl",
                                    typeof(Control),
                                    typeof(NumericButtonsControl),
                                    new PropertyMetadata(null));
    

    XAML:

    <my:NumericButtonsControl 
        x:Name="NumericButtons" 
        TargetControl="{Binding ElementName=DataEntryTextBox}" />
    

    【讨论】:

    • 酷。这样可行。我不知道如何用谷歌搜索这个问题。猜测的依赖属性很重要,但我真的不明白为什么......谢谢:)
    猜你喜欢
    • 2011-01-27
    • 1970-01-01
    • 2011-10-10
    • 1970-01-01
    • 1970-01-01
    • 2021-10-28
    • 2011-09-11
    • 2021-12-12
    • 2011-10-11
    相关资源
    最近更新 更多