【问题标题】:Using WPF Attached Properties to layout an LOB form使用 WPF 附加属性来布局 LOB 表单
【发布时间】:2024-01-31 01:25:02
【问题描述】:

我已经在我的应用程序中编写了许多数据输入类型的表单,我得出的结论是我需要让它变得更容易一些。在做了一些阅读之后,似乎可以使用子类 ItemsControl 来表示表单。

我已经这样做了,现在有类似的东西

<MySubClassedForm></MySubClassedForm>

我现在想做的是设置一个附加属性,比如“LabelText”,这样它就可以在内部的任何控件上使用。

举个例子,

<MySubClassedForm>
<TextBox MySubClassedForm.LabelText="Surname" />
<Image MySubClassedForm.LabelText="LabelText" />
</MySubClassedForm>

附加属性定义:-

 public static DependencyProperty LabelTextProperty = DependencyProperty.RegisterAttached("LabelText", typeof(string), typeof(MySubclassedForm),
         new UIPropertyMetadata(string.Empty));

        public string LabelText
        {
            get { return (string)GetValue(LabelTextProperty); }
            set { SetValue(LabelTextProperty, value); }
        }

我首先将附加属性放在 MySubClassedForm 上,然后出现以下错误:-
附加属性“MySubClassedForm.LabelText”未在“TextBox”或其基类之一上定义。 em>

请您告诉我我做错了什么以及我需要做些什么来完成这项工作?

谢谢亚历克斯

【问题讨论】:

  • 你是如何定义附加属性的?贴出代码。
  • 嗨,我本来想把它包括在内,但忘了。已编辑我的问题,现在将其包含在内。

标签: wpf xaml attached-properties lob


【解决方案1】:

您需要定义静态 getter 和 setter 方法:

public static readonly DependencyProperty LabelTextProperty =
    DependencyProperty.RegisterAttached(
        "LabelText", typeof(string), typeof(MySubclassedForm),
        new UIPropertyMetadata(string.Empty)); 

public static string GetLabelText(DependencyObject obj) 
{ 
    return (string)obj.GetValue(LabelTextProperty);
}

public static void SetLabelText(DependencyObject obj, string value) 
{ 
    obj.SetValue(LabelTextProperty, value); 
} 

Custom Attached Properties 上获取更多信息。

【讨论】:

    【解决方案2】:

    你应该看看magellan 它既有 WPF 表单引擎,又有优秀的 MVC 框架。任何一个都可以单独使用。

    它可以让你做

    <Form>
        <Field For="{Binding Path=Server.Server}" />
        <Field For="{Binding Path=Server.CachedExchangeMode}" />
        <Field For="{Binding Path=Server.Username}" />
        <Field For="{Binding Path=Server.SecurityMode}" />
    </Form>
    

    这将为您的视图模型上的属性自动生成正确的输入字段类型。

    【讨论】: