创建搜索框控件

Create Search Box Control

我正在尝试创建一个搜索文本框,其中有一个文本框区域和一个按钮。到目前为止,我实现了预期的布局:

<Style TargetType="{x:Type local:SearchTextBox}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type local:SearchTextBox}">
                    <Border Background="{TemplateBinding Background}"
                            BorderBrush="{TemplateBinding BorderBrush}"
                            BorderThickness="{TemplateBinding BorderThickness}">
                        <StackPanel Orientation="Horizontal"
                                          Width="200">
                            <TextBox Width="150" TextWrapping="Wrap" AcceptsReturn="True"/>
                            <Button Width="50" Content="Browse"></Button>
                        </StackPanel>
                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

然后我创建了控件:

static SearchTextBox()
 {
      DefaultStyleKeyProperty.OverrideMetadata(typeof(SearchTextBox), new FrameworkPropertyMetadata(typeof(SearchTextBox)));             
 }

 TextBox txtFileName = null;

 public TextBox TxtFileName
 {
     get { return txtFileName; }
     set { txtFileName = value; }
 }
 Button btnBrowse = null;

 public Button BtnBrowse
 {
      get { return btnBrowse; }
     set { btnBrowse = value; }
 }

现在我想访问这个按钮和文本框,这样我就可以单独定义它们的名称、内容等。

我该怎么做?

对于您的情况,您可以简单地使用 UserControls 来创建您的自定义控件。

这里是 link 创建示例用户控件。根据您的要求扩展控件

http://www.c-sharpcorner.com/UploadFile/mahesh/user-control-in-wpf/

在您的 class 中覆盖此方法。 public 虚空 OnApplyTemplate()。 然后创建并实例化您需要的控件。 沿着这些方向的东西:

GetTemplatechild 将允许您获取任何已定义的依赖对象。请给他们起个名字 (x:Name="foo").

public override void OnApplyTemplate()
{
    DependencyObject ButtonControlInTemplate = GetTemplateChild("searchbutton");// set the name as the x:Name for the controls in your xaml.
    Button SearchButton = (Button)ButtonControlInTemplate;
    DependencyObject TextBoxInTemplate = GetTemplateChild("searchinputfield"); // set the name as the x:Name for the controls in your xaml.
    TextBox InputTextBox = (TextBox)TextBoxInTemplate; 
    base.OnApplyTemplate();


}

注意。检查空值很重要,有时模板应用不正确。