【问题标题】:Attach property to usercontrol and updating it at design time将属性附加到用户控件并在设计时对其进行更新
【发布时间】:2012-03-21 22:36:47
【问题描述】:

如何创建像文本框这样的用户控件?例如,当我更改 Textbox 控件的 Text 属性时,新文本会出现在我当前正在使用的窗口中。

在我的项目中,我有很多地方需要用户输入信息,因此我想创建一个 InputField 用户控件。 (该用户控件由一个标签和一个具有自定义样式的文本框组成)

这是我的用户控件的 xaml:

<UserControl x:Class="PDV.UserControls.InputField"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
         mc:Ignorable="d" >
   <Grid>
      <StackPanel>
          <Label Content="{Binding Path=LblContent}" HorizontalAlignment="Left" VerticalAlignment="Top"  />
          <TextBox Height="23" Margin="5,-5,2,2" Name="textBox1" VerticalAlignment="Top" />
      </StackPanel>
   </Grid>
</UserControl>

以及该用户控件背后的代码:

namespace PDV.UserControls
{
    public partial class InputField : UserControl
    {
        public static DependencyProperty MessageProperty = DependencyProperty.Register(
            "LblContent", typeof(string), typeof(UserControl));

        public string LblContent{
            get{
                return (string)GetValue(MessageProperty);
            }
            set{
                SetValue(MessageProperty, value);
            }
        }

        //Constructor
        public InputField(){
            InitializeComponent();
            this.DataContext = this;
        }
    }
}

所以在我的主窗口中,我将能够通过以下方式使用该用户控件:

1) 导入该用户控件所在的命名空间:

  xmlns:myCtrl ="clr-namespace:PDV.UserControls"

2) 将该控件放置在该窗口中:

  <myCtrl:InputField LblContent="hello" Margin="0,0,483,0" Height="49" VerticalAlignment="Top"></myCtrl:InputField>

当我更新 LblContent="hello" 时,我必须怎么做才能在窗口上呈现? 在设计时呈现它会很好,而不仅仅是在运行时呈现

【问题讨论】:

  • 你确定你需要一个标签和文本框的自定义控件。您可以将样式应用于标签和文本框。并且标签将在设计时呈现。当您添加语法来绑定 TextBox 时,您并没有节省很多击键,而且在我看来,代码更难遵循。
  • 是的,我试图弄清楚这一点。标签和 textox 需要在堆栈面板内。我试图弄清楚如何为堆栈面板创建样式,以便其子项可以具有特定的样式,而不必为标签和堆栈面板的文本框创建样式。每次 y 需要一个新的输入字段时,我都必须放置三个控件,而不仅仅是拖动一个用户控件。

标签: c# wpf user-controls attached-properties


【解决方案1】:

我认为第二种可能是 InputField 公共静态 DependencyProperty MessageProperty = DependencyProperty.Register( "LblContent", typeof(string), typeof(InputField));

我从不尝试以您的方式设置 DataContext,最终尝试在用户控件 x:Name="Root" 处命名,然后像这样更改绑定:Content="{Binding Path=LblContent, ElementName=Root} "

【讨论】:

  • 因为我看到您以不同的方式管理数据上下文,但我在新帖子中插入了相同的评论。是的,我可以编辑它你是对的
猜你喜欢
  • 1970-01-01
  • 2013-03-25
  • 1970-01-01
  • 1970-01-01
  • 2010-09-05
  • 1970-01-01
  • 1970-01-01
  • 2021-02-17
  • 1970-01-01
相关资源
最近更新 更多