简体   繁体   中英

UserControl Dependency property does not work

I have my UserControl. I want to set Dependency property, but i can not.

TextBoxExtended.cs

public partial class TextBoxExtended : UserControl
    {
        public static readonly DependencyProperty MyTextPropertyProperty =
        DependencyProperty.Register("MyTextProperty", typeof(string), typeof(TextBoxExtended), new UIPropertyMetadata(String.Empty));

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

TextBoxExtended.xaml

<TextBox x:Name="tbMain" Text="{Binding MyTextProperty}"

MainWindow.xaml

<local:TextBoxExtended x:Name="TextBoxSearch" Height="30" Margin="83,38,193,285" MyTextProperty="MyTextProperty"/>

I need to event textchange, i use this code

<local:TextBoxExtended x:Name="TextBoxSearch" Height="30" Margin="83,38,193,285" MyTextProperty="{Binding MyText, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"/>

but I need to make the changes occurred after the introduction of each character

You'll have to set a source object of the Binding in TextBoxExtended.xaml, eg

<TextBox x:Name="tbMain"
    Text="{Binding MyTextProperty,
                   RelativeSource={RelativeSource AncestorType=UserControl}}" />

Use ElementName in Binding of TextBox.

  <StackPanel> <TextBox Text="{Binding MyText, ElementName=TextBoxSearch}" ></TextBox> <local:TextBoxExtended x:Name="TextBoxSearch" Height="30" MyText="Hello World!!!" /> </StackPanel> 

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