简体   繁体   中英

Create custom control with some property set through xaml

I created a custom control, deriving from a UserControl, it has a textblock, a textbox and 2 buttons, called PathMng.

<Grid>
    <!-- some other stuff -->
    <TextBlock Name="PathName">Name</TextBlock>
</Grid>

I'm trying to set the TextBlock's text through an external xaml calling this control

<Grid>
    <local:PathMng>NameHere</local:PathMng>
</Grid>

But I couldn't understand what do I have to do to bind the text "NameHere" to the TextBlock.

I tried to search with the words "custom xaml", "template xaml" or maybe-too-much-generic-words, but I couldn't find what I'm needed

Thanks in advance for any help

First, to make it simpler for you, set it using, for example:

<local:PathMng MyText="NameHere"/>

Now, in your user control code-behind, create a dependency property:

    public string MyText
    {
        get { return (string)GetValue(MyTextProperty); }
        set { SetValue(MyTextProperty, value); }
    }

    public static readonly DependencyProperty MyTextProperty =
        DependencyProperty.Register("MyText", typeof(string), typeof(UserContrrol1), new PropertyMetadata(null));

Finally, in your UserControl1 XAML, bind your TextBox's Text property to this DP:

<TextBox Text="{Binding MyText, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type local:UserControl1}}}" />

All this assumes your user control is called UserControl1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM